绘制条形图 - 颜色python

时间:2015-08-14 08:24:30

标签: python pandas matplotlib plot bar-chart

我有一个pandas数据框,我想将其绘制成条形图,数据具有以下形式;

Year   ISO  Value   Color 
2007   GBR  500     0.303
       DEU  444     0.875  
       FRA  987     0.777
2008   GBR  658     0.303
       USA  432     0.588  
       DEU  564     0.875
2009 ... etc

我试图按照以下方式迭代数据;

import matplotlib.pyplot as plt
import matplotlib.cm as cm 


conditions=np.unique[df['Color']]
plt.figure()
ax=plt.gca()
for i,cond in enumerate(conditions):
     print 'cond: ',cond
     df['Value'].plot(kind='bar', ax=ax, color=cm.Accent(float(i)/n))


     minor_XT=ax.get_xaxis().get_majorticklocs()
     df['ISO']=minor_XT
     major_XT=df.groupby(by=df.index.get_level_values(0)).first()['ISO'].tolist()
     df.__delitem__('ISO')
     plt.xticks(rotation=70)
     ax.set_xticks(minor_XT, minor=True)
     ax.set_xticklabels(df.index.get_level_values(1), minor=True, rotation=70)
     ax.tick_params(which='major', pad=45)
     _=plt.xticks(major_XT, (df.index.get_level_values(0)).unique(), rotation=0)
     plt.tight_layout()
     plt.show()

但这一切都用一种颜色,对我做错了什么建议?

1 个答案:

答案 0 :(得分:2)

由于df['Value'].plot(kind='bar')将绘制所有条形图,因此您无需迭代conditions。此外,由于plot(kind='bar')基本上调用了matplotlib.pyplot.bar,我们可以为它提供与数据数组长度相同的颜色列表,并使用这些颜色为每个条形图着色。这是一个略微简化的例子(我将让你弄清楚滴答和刻度标签):

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.cm as cm

df = pd.DataFrame([
    [2007,'GBR',500,0.303],
    [2007,'DEU',444,0.875],
    [2007,'FRA',987,0.777],
    [2008,'GBR',658,0.303],
    [2008,'USA',432,0.588],
    [2008,'DEU',564,0.875]],
    columns=['Year','ISO','Value','Color'])

colors = cm.Accent(df['Color']/len(df['Color']))

fig=plt.figure()
ax=fig.add_subplot(111)

df['Value'].plot(kind='bar',ax=ax,color=colors)

plt.show()

enter image description here