簡體   English   中英

將pyplot子圖與pandas lag_plot一起使用

[英]using pyplot subplots with pandas lag_plot

我正在嘗試使用熊貓的lag_plot模塊(Lag-1相關圖)制作具有多個子圖的圖形。 我正在用pyplot的標准“ subplots”命令嘗試此操作,但是當我嘗試在結果軸上調用“ lag_plot”時,它似乎並不喜歡它。 這是我的代碼:

c1, c2, c3, c4, c5 = sns.color_palette("husl", 5)
ax1 = plt.subplot2grid((3,2), (0,0))
ax2 = plt.subplot2grid((3,2), (0,1))
ax3 = plt.subplot2grid((3,2), (1,0))
ax4 = plt.subplot2grid((3,2), (1,1))
ax5 = plt.subplot2grid((3,2), (2,0))
ax1.lag_plot(d1, color = c1, alpha=0.5)
ax2.lag_plot(d2, color = c2, alpha=0.5)
ax3.lag_plot(d3, color = c3, alpha=0.5)
ax4.lag_plot(d4, color = c4, alpha=0.5)
ax4.lag_plot(d4, color = c5, alpha=0.5)

這是導致的錯誤:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
/home/iullah/<ipython-input-78-9deb0f435f22> in <module>()
      5 ax4 = plt.subplot2grid((3,2), (1,1))
      6 ax5 = plt.subplot2grid((3,2), (2,0))
----> 7 ax1.lag_plot(d1, color = c1, alpha=0.5)
      8 ax2.lag_plot(d2, color = c2, alpha=0.5)
      9 ax3.lag_plot(d3, color = c3, alpha=0.5)

AttributeError: 'AxesSubplot' object has no attribute 'lag_plot'

生成了正確的子圖陣列(2列和三行子圖,具有正確的軸),但是全部為空白(當然)。 那么,我在做什么錯呢? 使用熊貓繪圖功能時,還有另一種獲取多個子圖的方法嗎?

編輯:此代碼有效:

c1 = sns.color_palette("YlOrRd_r", 8)

plt.subplot(321)
lag_plot(d1, color = c1, alpha=0.5)

plt.subplot(322)
lag_plot(d2, color = c1, alpha=0.5)

plt.subplot(323)
lag_plot(d3, color = c1, alpha=0.5)

plt.subplot(324)
lag_plot(d4, color = c1, alpha=0.5)

plt.subplot(325)
lag_plot(d5, color = c1, alpha=0.5)

plt.show()

為什么該代碼有效,但第一個無效? 我非常喜歡用第一種方法,因為我可以做的事情使行和列共享軸標簽(使圖看起來更清晰),而這是第二組代碼無法做到的。

您應該在數據上調用plotting命令並為其賦予matplotlib軸:

c1, c2, c3, c4, c5 = sns.color_palette("husl", 5)
ax1 = plt.subplot2grid((3,2), (0,0))
ax2 = plt.subplot2grid((3,2), (0,1))
ax3 = plt.subplot2grid((3,2), (1,0))
ax4 = plt.subplot2grid((3,2), (1,1))
ax5 = plt.subplot2grid((3,2), (2,0))
d1.lag_plot(ax=ax1, color = c1, alpha=0.5)
d2.lag_plot(ax=ax2, color = c2, alpha=0.5)
d3.lag_plot(ax=ax3, color = c3, alpha=0.5)
d4.lag_plot(ax=ax4, color = c4, alpha=0.5)

您可以通過ax=...參數將軸提供給lag_plot函數:

from pandas.tools.plotting import lag_plot

df = pd.DataFrame ( { ch: np.random.randn(100) for ch in 'AB' } )
fig = plt.figure( )
ax = fig.add_axes( [.05, .05, .9, .9] )

lag_plot( df.A, ax=ax)
lag_plot( df.B, ax=ax, color='Red'  )

暫無
暫無

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

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