【问题标题】:Two matplotlib/pyplot histograms with the same axes or on the same figure两个 matplotlib/pyplot 直方图,轴相同或在同一个图上
【发布时间】:2016-01-02 06:30:01
【问题描述】:

我尝试制作两个分布不同的直方图。我想在彼此旁边或顶部显示,但我不确定如何使用 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() 设置/读取范围,但这似乎只是指最近创建的图。

我也意识到分箱也可能导致问题,所以我想我需要使用适用于两个数字的分箱。

【问题讨论】:

  • 他们在上面写的代码会在同一个图上生成两个图,我不太确定你在这里问什么
  • 我刚刚意识到我的问题是将绘图语句放在两个单独的 ipython 代码单元中。它会在每个单元格之后创建一个图。当我在同一个单元格中运行它们时,它可以工作。谢谢!

标签: python matplotlib ipython data-visualization ipython-notebook


【解决方案1】:

你的要求真的不清楚。我想这是因为你没有完全理解 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 的图形对象,其中包含两个 Axes 对象,分别名为 ax1ax2。 Axes 对象是您绘制图形的地方。所以,这里我们在一个有 1 行和 2 行的网格上创建一个有 2 个轴的图形。你可以使用

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

并致电ax[0]ax[1]

您可以通过调用以下方式获得 2 个地块:

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

然后您可以在给定的 Ax 中绘制您想要的直方图。它们会自动缩放。

所以如果你想改变一个轴,比如 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)

希望对你有帮助

【讨论】:

  • 谢谢!我会试试这个,但我也刚刚发现,如果我在同一个 ipython 代码单元格中创建这两个直方图,它们会被添加到同一个图中。
【解决方案2】:

感谢 ajay 的评论,解决了问题。我的问题是我有一个带有第一个绘​​图命令的 ipython 单元格和一个带有第二个绘图命令的第二个单元格。 inline 选项意味着在每个单元格运行后创建一个图。如果我将两个绘图命令放在一个单元格中,它会创建一个包含两个直方图的图表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-04
    • 1970-01-01
    • 2015-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多