我有两个直方图,我试图制作它们具有不同的分布。我想将其显示在彼此旁边或之上,但我不知道如何使用 pyplot 来做到这一点。如果我分别绘制它们,则两个图的轴永远不会相同。我正在尝试在 ipython 笔记本中执行此操作。这是一个例子。
import numpy as np
import pylab as P
%matplotlib inline
mu, sigma = 200, 25
x = mu + sigma*P.randn(10000)
n, bins, patches = P.hist(x, 50, normed=1, histtype='stepfilled')
mu2, sigma2 = 250, 45
x2 = mu2 + sigma2*P.randn(10000)
n2, bins2, patches2 = P.hist(x2, 50, normed=1, histtype='stepfilled')
此代码创建两个单独的图,每个图在生成时都会打印。是否可以保存这些图而不是打印它们,确定两个图中 y 和 x 范围的最大/最小值,然后调整每个图的范围以使它们具有可比性?我知道我可以使用 P.ylim() 和 P.xlim() 设置/读取范围,但这似乎仅指最近创建的数字。
我还意识到分箱也可能会导致问题,所以我想我需要使用适用于这两个数字的分箱。
最佳答案
你问的问题实在是不清楚。我猜是因为你没有完全理解matplotlib。这是一个快速演示。其余的,请阅读文档:http://matplotlib.org/
要在一个图中显示不同的图,您需要创建一个包含子图的图对象。您需要导入 matplotlib.pyplot
才能完全轻松地访问 matplotlib 中的绘图工具。
这是您修改后的代码:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline # only in a notebook
mu, sigma = 200, 25
x = mu + sigma*np.random.randn(10000)
fig, [ax1, ax2] = plt.subplots(1, 2)
n, bins, patches = ax1.hist(x, 50, normed=1, histtype='stepfilled')
mu2, sigma2 = 250, 45
x2 = mu2 + sigma2*np.random.randn(10000)
n2, bins2, patches2 = ax2.hist(x2, 50, normed=1, histtype='stepfilled')
因此,我将 P.randn
更改为 np.random.randn
,因为我不再导入 pylab。
关键行如下:
fig, [ax1, ax2] = plt.subplots(1, 2)
我们在其中创建一个名为 fig
的图形对象,其中包含名为 ax1
和 ax2
的 2 个 Axes 对象。 Axes 对象是您绘制图表的地方。因此,我们在这里创建一个在具有 1 行和 2 行的网格上具有 2 个轴的图形。你本来可以使用
fig, ax = plt.subplots(1, 2)
并调用ax[0]
和ax[1]
。
您可以通过调用以下方式获得两张图:
fig, ax = plt.subplots(2, 1)
然后您可以在给定的 Axe 中绘制您想要的直方图。它们会自动缩放。
因此,如果您想更改一个轴(例如 X 轴)以使两者具有相同的轴,您可以执行以下操作:
ax_min = min(ax1.get_xlim()[0], ax2.get_xlim()[0]) # get minimum of lower bounds
ax_max = max(ax1.get_xlim()[1], ax2.get_xlim()[1]) # get maximum of upper bounds
ax1.set_xlim(ax_min, ax_max)
ax2.set_xlim(ax_min, ax_max)
希望这有帮助
关于python - 两个具有相同轴或在同一图形上的 matplotlib/pyplot 直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32951332/