【问题标题】:Pandas: plotting two histograms on the same plotPandas:在同一个图上绘制两个直方图
【发布时间】:2015-01-10 18:44:30
【问题描述】:

我想让 2 个直方图出现在同一个图上(使用不同的颜色,并且可能有不同的 alpha)。我试过了

import random
x = pd.DataFrame([random.gauss(3,1) for _ in range(400)])
y = pd.DataFrame([random.gauss(4,2) for _ in range(400)])


x.hist( alpha=0.5, label='x')
y.hist(alpha=0.5, label='y')
x.plot(kind='kde', style='k--')
y.plot(kind='kde', style='k--')

plt.legend(loc='upper right')
plt.show()

这会在 4 个不同的图中产生结果。我怎样才能让它们在同一个上?

【问题讨论】:

    标签: python pandas histogram


    【解决方案1】:

    如果我理解正确,两个历史应该进入同一个子图。所以应该是

    fig = plt.figure()
    ax = fig.add_subplot(111)
    _ = ax.hist(x.values)
    _ = ax.hist(y.values, color='red', alpha=.3)
    

    您还可以将 pandas 的 plot 方法传递给一个轴对象,所以如果您希望两个 kde 都在另一个图中,请执行以下操作:

    fig = plt.figure()
    ax = fig.add_subplot(111)
    x.plot(kind='kde', ax=ax)
    y.plot(kind='kde', ax=ax, color='red')
    

    要将所有内容放在一个图中,您需要两个不同的 y 尺度,因为 kde 是密度,直方图是频率。为此,您使用axes.twinx() 命令。

    fig = plt.figure()
    ax = fig.add_subplot(111)
    _ = ax.hist(x.values)
    _ = ax.hist(y.values, color='red', alpha=.3)
    
    ax1 = ax.twinx()
    x.plot(kind='kde', ax=ax1)
    y.plot(kind='kde', ax=ax1, color='red')
    

    【讨论】:

    • 谢谢,这几乎可以工作了!我现在在一个图中有两个直方图,在另一个图中有两个 kde。如何将所有这些合并到同一个图中?运行你所有的代码,没有第二个 fig = ... 仍然给我 2 个不同的情节。
    • 好吧,kde(密度)有另一个尺度作为直方图(频率),所以你必须使用ax.twinx() 引入第二个 y 尺度,就像这里:link。将在几秒钟内更新我的答案
    • 第一个解决方案的问题在于计数由 bin 宽度决定。如果它们不同,则垂直轴无法比较。
    • @rustil 这个解决方案还可行吗?我不这么认为。
    【解决方案2】:

    您可以使用 plt.figure() 和函数 add_subplot():前 2 个参数是您想要在图中显示的行数和列数,最后一个是子图在图中的位置。

    fig = plt.figure()
    subplot = fig.add_subplot(1, 2, 1)
    subplot.hist(x.ix[:,0], alpha=0.5)
    subplot = fig.add_subplot(1, 2, 2)
    subplot.hist(y.ix[:,0], alpha=0.5)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-15
      • 1970-01-01
      相关资源
      最近更新 更多