簡體   English   中英

熊貓:在同一個地塊上繪制兩個直方圖

[英]Pandas: plotting two histograms on the same plot

我想有2個直方圖出現在同一個圖上(有不同的顏色,可能還有不同的alphas)。 我試過了

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個不同圖的結果。 我怎么能把它們放在同一個?

如果我理解正確的話,兩個his應該進入同一個子情節。 所以它應該是

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')

您可以使用plt.figure()和函數add_subplot():前兩個參數是您在繪圖中所需的行數和列數,最后一個是繪圖中子圖的位置。

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM