2017-06-12 35 views
1

如何繪製條形圖的條形圖不同顏色只有使用熊貓數據框plot方法?熊貓數據框條形圖 - 繪圖條從特定色表映射條不同顏色

如果我有這樣的數據幀:

df = pd.DataFrame({'count': {0: 3372, 1: 68855, 2: 17948, 3: 708, 4: 9117}}).reset_index() 

    index count 
0  0 3372 
1  1 68855 
2  2 17948 
3  3 708 
4  4 9117 

什麼df.plot()爭論是否需要設置成圖中的每個條:

  1. 採用「配對」顏色表
  2. 每塊試驗田吧不同的顏色

我在試圖:

df.plot(x='index', y='count', kind='bar', label='index', colormap='Paired', use_index=False) 

結果:

not different colors

我已經知道(是的,這工作,但同樣,我目的是要弄清楚如何與只有做到這一點。當然,它必須能夠):

def f(df): 
    groups = df.groupby('index') 

    for name,group in groups: 
    plt.bar(name, group['count'], label=name, align='center') 

    plt.legend() 
    plt.show() 

end result but used for loop

回答

1

沒有參數,你可以傳遞給是不同colorizes酒吧的一列。
因爲對於不同的列條着色的不同,選項是繪製前轉數據框,

ax = df.T.plot(kind='bar', label='index', colormap='Paired') 

現在,這將繪製數據作爲子組的一部分。因此需要應用一些調整來正確設置限制和xlabels。

import matplotlib.pyplot as plt 
import pandas as pd 

df = pd.DataFrame({'count': {0: 3372, 1: 68855, 2: 17948, 3: 708, 4: 9117}}).reset_index() 

ax = df.T.plot(kind='bar', label='index', colormap='Paired') 
ax.set_xlim(0.5, 1.5) 
ax.set_xticks([0.8,0.9,1,1.1,1.2]) 
ax.set_xticklabels(range(len(df))) 
plt.show() 

enter image description here

雖然我猜這個解決方案的標準從匹配的問題,實際上是沒有錯的使用plt.bar。到plt.bar單個呼叫足以

plt.bar(range(len(df)), df["count"], color=plt.cm.Paired(np.arange(len(df)))) 

enter image description here

完整代碼:

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

df = pd.DataFrame({'count': {0: 3372, 1: 68855, 2: 17948, 3: 708, 4: 9117}}).reset_index() 

plt.bar(range(len(df)), df["count"], color=plt.cm.Paired(np.arange(len(df)))) 

plt.show()