python - 绘制条形图-colors python

标签 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()

但全部都是一种颜色,关于我做错了什么有什么建议吗?

最佳答案

由于 df['Value'].plot(kind='bar') 将绘制所有条形图,因此您无需迭代条件。此外,由于 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

关于python - 绘制条形图-colors python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32005510/

相关文章:

Python:从迭代器内的列表中删除元素?

python - 使用列表指定 pandas 列

python - 将 (MultiIndex) Dataframe 转换为字典列表

python - 查找数据子集上方和下方多行的有效方法

python - matplotlib barplot 的最后一个栏被填充了一半

python - 如何在Python中的单个列表中根据给定的x,y值绘制不同的线?

python - Seaborn Pairplot Pearsons P 统计量

python - 如何显示 blobstore 中的图像?

python - 为什么 Python 使用以下代码知道答案按字母顺序排列是正确的?

python - 在 Django 中非规范化数据的最佳方法?