如何重用matplotlib.Axes.hist的返回值?

sds*_*sds 5 python matplotlib histogram

假设我想绘制两次相同数据的直方图:

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(8,6))
ax1,ax2 = fig.subplots(nrows=2,ncols=1)
ax1.hist(foo)
ax2.hist(foo)
ax2.set_yscale("log")
ax2.set_xlabel("foo")
fig.show()
Run Code Online (Sandbox Code Playgroud)

请注意,我打了两次电话,而且可能会很贵。我想知道是否有一种简单的方法可以重用第一次调用的返回值以使第二次调用便宜。Axes.hist

tdy*_*tdy 5

ax.hist文档中,有一个重用np.histogram输出的相关示例:

weights参数可用于绘制已分箱的数据的直方图,方法是将每个箱视为权重等于其计数的单个点。

counts, bins = np.histogram(data)
plt.hist(bins[:-1], bins, weights=counts)
Run Code Online (Sandbox Code Playgroud)

我们可以使用相同的方法,ax.hist因为它还返回计数和 bin(以及 bar 容器):

x = np.random.default_rng(123).integers(10, size=100)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 3))

counts, bins, bars = ax1.hist(x)          # original hist
ax2.hist(bins[:-1], bins, weights=counts) # rebuilt via weights params
Run Code Online (Sandbox Code Playgroud)

通过权重参数重建


或者,使用重建原始直方图ax.bar并重新设置宽度/对齐方式以匹配ax.hist

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 3))

counts, bins, bars = ax1.hist(x)                    # original hist
ax2.bar(bins[:-1], counts, width=1.0, align='edge') # rebuilt via ax.bar
Run Code Online (Sandbox Code Playgroud)

通过 ax.bar 重建