2017-09-06 84 views
1

我想將溫度數據繪製爲線條,並將降雨數據作爲條形圖。我可以在Excel中輕鬆完成此操作,但我更喜歡花哨的Python圖形以更好的方式顯示它。使用matplotlib在同一圖表上繪製來自熊貓數據框的線條和條形圖

一些示例代碼來說明這個問題:

import pandas as pd 
import numpy as np 
import matplotlib.pyplot as plt 
%matplotlib inline 

dates = pd.date_range('20070101',periods=365) 
df = pd.DataFrame(data=np.random.randint(0,50,(365,4)), columns =list('ABCD')) 
df['date'] = dates 
df = df[['date','A', 'B', 'C', 'D']] 
df.set_index(['date'],inplace=True) #set date as the index so it will plot as x axis 

這產生具有四個列(想象A和B是溫度和C和d是降雨)一個數據幀。

我想繪製降雨酒吧,和臨時作爲一條線,但是當我嘗試這樣做:

ax = df.plot(y="A", kind="bar") 
df.plot(y="B", kind = "line", ax = ax) 

線條情節,not the bars.

這是一個簡單得多的版本是什麼我試圖做,但我認爲它說明了這個問題。

編輯:

下面的代碼工作:

fig, ax= plt.subplots() 

ax.plot_date(df.index, df.iloc[:,2], '-') 

for i in range(3): 
    diff = df.index[1]-df.index[0] 
    spacing = diff/(1.3*len(df.columns)) 
    ax.bar(df.index+(-5+i)*spacing, df.iloc[:,i], 
     width=spacing/diff, label=df.columns[i]) 

plt.legend() 
plt.gcf().autofmt_xdate() 
plt.show() 

真的很感激,不太複雜的答案,這似乎相當冗長,但它似乎工作!

+0

x-軸是不相容的(嘗試繪製兩個分開)。 – IanS

+0

相關:https://stackoverflow.com/questions/30133280/pandas-bar-plot-changes-date-format – IanS

+0

我編輯了這個問題來回應你的建議,根據日期創建了一個新的x軸,但結果是一樣的 – Pad

回答

1

一個簡單的方法是使用x_compat屬性:

ax = df.plot(x=index, y="A", x_compat=True) # plot lines first 
df.plot(x=index, y="B", kind="bar", ax=ax) 

,然後可以調整節拍頻率。

帽尖:https://stackoverflow.com/a/39907390/5276797

+0

對不起 - 但是這隻會繪製條形圖,而不是線條? – Pad

+1

我的不好,我貼錯了嘗試。您仍然需要'x = index',請參閱我的編輯。 – IanS

+0

它到底有效嗎? – IanS

相關問題