备注
前往结尾 以下载完整示例代码。
带有直方图的散点图#
在散点图的两侧显示边缘分布作为直方图。
为了使主坐标轴与边缘坐标轴对齐,下面展示了两种选项:
虽然 Axes.inset_axes 可能稍微复杂一些,但它允许正确处理具有固定纵横比的主 Axes。
使用 axes_grid1 工具包生成类似图形的另一种方法,请参见 使用可定位的轴将直方图与散点图对齐 示例。最后,也可以使用 Figure.add_axes 以绝对坐标定位所有 Axes(此处未展示)。
首先,我们定义一个函数,该函数接受 x 和 y 数据作为输入,以及三个 Axes,主 Axes 用于散点图,以及两个边缘 Axes。然后,它将在提供的 Axes 内创建散点图和直方图。
import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility
np.random.seed(19680801)
# some random data
x = np.random.randn(1000)
y = np.random.randn(1000)
def scatter_hist(x, y, ax, ax_histx, ax_histy):
# no labels
ax_histx.tick_params(axis="x", labelbottom=False)
ax_histy.tick_params(axis="y", labelleft=False)
# the scatter plot:
ax.scatter(x, y)
# now determine nice limits by hand:
binwidth = 0.25
xymax = max(np.max(np.abs(x)), np.max(np.abs(y)))
lim = (int(xymax/binwidth) + 1) * binwidth
bins = np.arange(-lim, lim + binwidth, binwidth)
ax_histx.hist(x, bins=bins)
ax_histy.hist(y, bins=bins, orientation='horizontal')
使用 gridspec 定义轴的位置#
我们定义了一个具有不等宽度和高度比的gridspec,以实现所需的布局。另请参阅 在图形中排列多个轴 教程。
# Start with a square Figure.
fig = plt.figure(figsize=(6, 6))
# Add a gridspec with two rows and two columns and a ratio of 1 to 4 between
# the size of the marginal Axes and the main Axes in both directions.
# Also adjust the subplot parameters for a square plot.
gs = fig.add_gridspec(2, 2, width_ratios=(4, 1), height_ratios=(1, 4),
left=0.1, right=0.9, bottom=0.1, top=0.9,
wspace=0.05, hspace=0.05)
# Create the Axes.
ax = fig.add_subplot(gs[1, 0])
ax_histx = fig.add_subplot(gs[0, 0], sharex=ax)
ax_histy = fig.add_subplot(gs[1, 1], sharey=ax)
# Draw the scatter plot and marginals.
scatter_hist(x, y, ax, ax_histx, ax_histy)

使用 inset_axes 定义轴的位置#
inset_axes 可以用于将边缘图放置在主Axes的*外部*。这样做的优点是主Axes的纵横比可以固定,并且边缘图将始终相对于Axes的位置绘制。
# Create a Figure, which doesn't have to be square.
fig = plt.figure(layout='constrained')
# Create the main Axes, leaving 25% of the figure space at the top and on the
# right to position marginals.
ax = fig.add_gridspec(top=0.75, right=0.75).subplots()
# The main Axes' aspect can be fixed.
ax.set(aspect=1)
# Create marginal Axes, which have 25% of the size of the main Axes. Note that
# the inset Axes are positioned *outside* (on the right and the top) of the
# main Axes, by specifying axes coordinates greater than 1. Axes coordinates
# less than 0 would likewise specify positions on the left and the bottom of
# the main Axes.
ax_histx = ax.inset_axes([0, 1.05, 1, 0.25], sharex=ax)
ax_histy = ax.inset_axes([1.05, 0, 0.25, 1], sharey=ax)
# Draw the scatter plot and marginals.
scatter_hist(x, y, ax, ax_histx, ax_histy)
plt.show()

参考文献
以下函数、方法、类和模块的使用在本示例中展示: