2016-02-25 293 views
2

我有一個3列的數據框:其中一個是「groupby」列,另外兩個是具有值的「正常」列。我想要生成一個boxplot和一個條形圖。在條形圖上,我想要顯示每個組元素的出現次數。讓我的示例代碼告訴這個數據幀中更詳細:Python熊貓繪製移位x軸如果twinx兩個y軸

li_str = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'] 

df = pd.DataFrame([[i]+j[k] for i,j in {li_str[i]:np.random.randn(j, 2).tolist() for i,j in \ 
    enumerate(np.random.randint(5, 15, len(li_str)))}.items() for k in range(len(j))] 
    , columns=['A', 'B', 'C']) 

所以上面我產生隨機數的隨機數到li_str每一個元素,我做它列BC

然後我可視化只的箱線圖:

fig, ax = plt.subplots(figsize=(16,6)) 
p1 = df.boxplot(ax=ax, column='B', by='A', sym='') 

我的結果是: enter image description here

現在我形象化元件每個基團具有的數量(所以我np.random.randint(5, 15, len(li_str))代碼上述生成的隨機數) :

fig, ax = plt.subplots(figsize=(16,6)) 

df_gb = df.groupby('A').count() 

p2 = df_gb['B'].plot(ax=ax, kind='bar', figsize=(16,6), colormap='Set2', alpha=0.3) 
plt.ylim([0, 20]) 

我的結果是: enter image description here

,現在我想一個圖這兩個:

fig, ax = plt.subplots(figsize=(16,6)) 
ax2 = ax.twinx() 

df_gb = df.groupby('A').count() 

p1 = df.boxplot(ax=ax, column='B', by='A', sym='') 
p2 = df_gb['B'].plot(ax=ax2, kind='bar', figsize=(16,6) 
    , colormap='Set2', alpha=0.3, secondary_y=True) 
plt.ylim([0, 20]) 

我的結果是: enter image description here

有誰知道爲什麼我的箱線圖被右移一個x軸的刻度?我使用Python 3.5.1,pandas 0.17.0,matplotlib 1.4.3

謝謝!!!

回答

2

這是因爲即使標籤相同,boxplot和條形圖也不使用相同的xticks。

df.boxplot(column='B', by='A') 
plt.xticks() 

(array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), <a list of 10 Text xticklabel objects>) 

df.groupby('A').count()['B'].plot(kind='bar') 
plt.xticks() 

(array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), <a list of 10 Text xticklabel objects>) 

一瞥,它看起來對我來說,這應該是固定在matplotlib boxplot()不一致,但我可能只是俯瞰的理由。

作爲一種變通方法使用matplotlib bar(),它允許你指定xticks以匹配箱線圖(我沒有找到一種方法與df.plot(kind='bar')做到這一點。

df.boxplot(column='B', by='A') 
plt.twinx() 
plt.bar(left=plt.xticks()[0], height=df.groupby('A').count()['B'], 
     align='center', alpha=0.3) 

enter image description here

+0

謝謝我的問題是現在我想繪製平均值(這是一條簡單的線),但matplotlib'plt.plot()'和pandas'df.plot()'都適用於我。說我不能指定這些功能的xticks :( – ragesz