2014-06-12 68 views
15

我有一個數據幀尋找這樣的:熊貓:酒吧積有兩個條和兩個Y軸

 amount  price 
age 
A  40929 4066443 
B  93904 9611272 
C 188349 19360005 
D 248438 24335536 
E 205622 18888604 
F 140173 12580900 
G  76243 6751731 
H  36859 3418329 
I  29304 2758928 
J  39768 3201269 
K  30350 2867059 

現在,我想繪製一個酒吧,陰謀與年齡在x軸作爲標籤。對於每個x-tick,應該有兩個小節,一個小節爲數量,一個爲價格。我可以通過簡單地使用這個工作:

df.plot(kind='bar') 

問題是縮放。價格是如此之高,我真的不能確定在該圖中的金額,請參閱:

enter image description here

因此,我想第二個y軸。我試過它使用:

df.loc[:,'amount'].plot(kind='bar') 
df.loc[:,'price'].plot(kind='bar',secondary_y=True) 

但這只是覆蓋酒吧,並沒有把他們並排放置。 有沒有辦法做到這一點,而不必訪問較低級別的matplotlib(這顯然可以通過手動並排放置酒吧)?

現在,我用兩個單地塊的次要情節中:

df.plot(kind='bar',grid=True,subplots=True,sharex=True); 

導致:

enter image description here

回答

35

使用新的大熊貓版本(0.14.0或更高版本)以下代碼將起作用。要創建兩個軸,我手動創建了兩個matplotlib軸對象(axax2),它們將用於這兩個柱狀圖。

繪製數據框時,您可以使用ax=...來選擇軸對象。此外,爲了防止兩個圖重疊,我修改了它們與position關鍵字參數對齊的位置,但默認爲0.5,但這意味着兩個條形圖重疊。

import matplotlib.pyplot as plt 
import numpy as np 
import pandas as pd 
from io import StringIO 

s = StringIO("""  amount  price 
A  40929 4066443 
B  93904 9611272 
C 188349 19360005 
D 248438 24335536 
E 205622 18888604 
F 140173 12580900 
G  76243 6751731 
H  36859 3418329 
I  29304 2758928 
J  39768 3201269 
K  30350 2867059""") 

df = pd.read_csv(s, index_col=0, delimiter=' ', skipinitialspace=True) 

fig = plt.figure() # Create matplotlib figure 

ax = fig.add_subplot(111) # Create matplotlib axes 
ax2 = ax.twinx() # Create another axes that shares the same x-axis as ax. 

width = 0.4 

df.amount.plot(kind='bar', color='red', ax=ax, width=width, position=1) 
df.price.plot(kind='bar', color='blue', ax=ax2, width=width, position=0) 

ax.set_ylabel('Amount') 
ax2.set_ylabel('Price') 

plt.show() 

Plot

+0

該多好啊,不知道了'ax'參數。 Thx – tim

+0

這太棒了!但是...如果我將其中一個值改爲負值,那麼結果就會中斷。任何想法如何解決它? – Dror

+0

這太好了。但傳說只出現藍色,而不是兩個。 –

6

這裏是另一種方法:

  • 創建左側所有的酒吧軸
  • 舉動改變一些酒吧向右軸這是transform屬性

這裏是代碼:

import pylab as pl 
df = pd.DataFrame(np.random.rand(10, 2), columns=["left", "right"]) 
df["left"] *= 100 

ax = df.plot(kind="bar") 
ax2 = ax.twinx() 
for r in ax.patches[len(df):]: 
    r.set_transform(ax2.transData) 
ax2.set_ylim(0, 2); 

這裏是輸出:

enter image description here

+0

不錯的一個,謝謝關於ax.patches :-) – tim

+0

的提示,如果你想'縮放'值,你應該使用'ax.patches [:len(df)]''。只是在說' :)。真棒和簡潔的答案! –