簡體   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