【问题标题】:Colouring the bars of a bar graph differently using pandas and matplotlib [duplicate]使用熊猫和matplotlib对条形图的条形进行不同的着色[重复]
【发布时间】:2018-02-19 11:00:03
【问题描述】:

所以我的数据看起来像

    Manufacturer       Mean
0            DAF  57.036199
1           Fiat  42.296814
2           Ford  54.546769
3          Iveco  41.678711
4            MAN  50.764308
5  Mercedes Benz  49.093340
6        Renault  47.384080
7         Scania  46.317282
8     Volkswagen  50.938158
9          Volvo  43.382830

我正在尝试使用上述数据绘制条形图。我希望 48 以上的值有不同的颜色,底部的 3 有不同的颜色。我尝试使用下面的代码,但它给了我以下错误:

TypeError: unsupported operand type(s) for -: 'str' and 'float'

我为制作图表而编写的代码:

plt.figure()
plt.bar(meansOfRoadGoingVehicles_sort['Manufacturer'], meansOfRoadGoingVehicles_sort['Mean'])
plt[0:7].set_color('b')
plt[6].set_color('grey')
plt[8:11].set_color('r')
plt.show()

【问题讨论】:

  • 试试df.plot.bar()df.set_index('Manufacturer').plot.bar()
  • 如果有任何答案满足你的解决方案,请在左侧用绿色勾号标记。

标签: python pandas matplotlib graph-coloring


【解决方案1】:

问题是plt.bar() 需要条形的坐标。您可以以range(len(df)) 的方式在 x 轴上放置一个列表,然后更改刻度。对于颜色,您可以创建颜色列表并将其分配给每个条形图。希望它有用:

cars_dict = {
        u"DAF": [57.036199],
        u"Fiat": [42.296814],
        u"Ford": [54.546769],
        u"Iveco": [41.678711],
        u"MAN": [50.764308],
        u"Renault": [47.384080],
        u"Scania": [46.317282],
        u"Volkswagen": [50.938158],
        u"Volvo": [43.382830]
    }
df = pd.DataFrame(cars_dict).T.reset_index()
df.columns = [u"Manufacturer", u"Mean"]

colors = ['b']*6+['grey']+['r']*3
plt.figure()
barlist = plt.bar(range(len(df)), df['Mean'].values)
plt.xticks(range(len(df)),df['Manufacturer'].values,rotation=90)
bars = [bar.set_color(colors[i]) 
            for i, bar in enumerate(barlist)]
plt.show()

【讨论】:

    猜你喜欢
    • 2017-05-13
    • 2015-06-28
    • 2017-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-15
    • 2019-04-13
    • 2017-04-01
    相关资源
    最近更新 更多