如何重新使用 matplotlib.Axes.hist 的 return 值?
How to re-use the return values of matplotlib.Axes.hist?
假设我想绘制两次相同数据的直方图:
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()
请注意,我调用了 Axes.hist
两次 ,这可能很昂贵。我想知道是否有一种 easy 方法可以重新使用第一个调用的 return 值来使第二个调用便宜。
在ax.hist
docs, there is a related example of reusing np.histogram
输出中:
The weights
parameter can be used to draw a histogram of data that has already been binned by treating each bin as a single point with a weight equal to its count.
counts, bins = np.histogram(data)
plt.hist(bins[:-1], bins, weights=counts)
我们可以对 ax.hist
使用相同的方法,因为它也 returns 计数和分箱(以及条形容器):
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
或者,使用 ax.bar
重建原始直方图并重新设置 width/alignment 样式以匹配 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
假设我想绘制两次相同数据的直方图:
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()
请注意,我调用了 Axes.hist
两次 ,这可能很昂贵。我想知道是否有一种 easy 方法可以重新使用第一个调用的 return 值来使第二个调用便宜。
在ax.hist
docs, there is a related example of reusing np.histogram
输出中:
The
weights
parameter can be used to draw a histogram of data that has already been binned by treating each bin as a single point with a weight equal to its count.counts, bins = np.histogram(data) plt.hist(bins[:-1], bins, weights=counts)
我们可以对 ax.hist
使用相同的方法,因为它也 returns 计数和分箱(以及条形容器):
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
或者,使用 ax.bar
重建原始直方图并重新设置 width/alignment 样式以匹配 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