繁体   English   中英

具有相同轴或相同图形的两个matplotlib / pyplot直方图

[英]Two matplotlib/pyplot histograms with the same axes or on the same figure

我试图使两个直方图具有不同的分布。 我想显示然后彼此相邻或重叠,但是我不确定如何用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的图形对象,并在ax1ax2包含2个Axes对象。 轴对象是您绘制图形的地方。 因此,在这里我们在具有1条线和2行的网格上创建具有2个轴的图形。 你可能已经用过

fig, ax = plt.subplots(1, 2)

并调用ax[0]ax[1]

您可以通过调用以下命令获得2个地块,一个在另一个地块上:

fig, ax = plt.subplots(2, 1)

然后,您可以在给定的轴上绘制所需的直方图。 它们将自动缩放。

因此,如果您想更改一个轴(例如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)

希望这可以帮助

由于阿杰的评论,找出了问题所在。 我的问题是我在第一个plot命令中有一个ipython单元,在第二个plot命令中有第二个单元。 内联选项表示在运行每个单元格后创建了一个图。 如果将两个plot命令放到一个单元格中,它将创建带有两个直方图的单个图表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM