1

So I have data that looks like

    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

I am trying to plot a bar graph using the above data. I want the values above 48 to be coloured differently and the bottom 3 to be coloured differently. I tried using the code below but it gives me the following error:

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

The code I have written to make the graph:

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()
Mabel Villalba
  • 2,538
  • 8
  • 19
paddy
  • 123
  • 1
  • 2
  • 13

1 Answers1

0

The problem is that plt.bar() requires the coordinates of the bars. You can put a list in the x axis in the manner range(len(df))and then change the ticks. For the colors you can create a list of colors and assign it to each bar. Hope it serves:

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

enter image description here

arturomp
  • 28,790
  • 10
  • 43
  • 72
Mabel Villalba
  • 2,538
  • 8
  • 19