0

Question: How do I highlight one bar in a bar graph in Python? I have a Dataframe with two columns : Year (years from 1994-2020) and Fatalities (number of car crash fatalities per year).

I'm trying to plot a bar graph and highlight the year 2020.

Code I have tried

fig, ax = plt.subplots()

colors = []
if fatality_94_20[fatality_94_20['Year']==2020]:
   colors = 'orange'
else:
   colors = 'cornflowerblue'


with sns.axes_style("whitegrid"):
    ax = ax.bar(fatality_94_20['Year'], fatality_94_20['Fatalities'], color = 'colors')
    

plt.title('Total Car Crash Fatalities \n per Year', x = .50, y = 1.00, size = 18)


plt.xlabel('Years', size = 16)
plt.ylabel('Fatalities', size = 16)


plt.xticks(rotation = 90, size = 14)
plt.yticks(size = 14)


plt.show()

I am getting the error: ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Here is a screenshot of the graph without the highlighted bar. :

Graph without highlighted bar

When I do just the code:

fatality_94_20[fatality_94_20['Year']==2020]

I do get the correct data. Thanks

dat.a.tho
  • 59
  • 7
  • 2
    Try looking [here](https://stackoverflow.com/questions/18973404/setting-different-bar-color-in-matplotlib-python) or [here](https://stackoverflow.com/questions/18903750/vary-the-color-of-each-bar-in-bargraph-using-particular-value) for ideas – ramzeek Mar 27 '22 at 16:08
  • 1
    You could do something like `ax.bar(fatality_94_20['Year'], fatality_94_20['Fatalities'], color=['skyblue'] * (len(fatality_94_20) - 1) + ['tomato'])` to highlight the last bar (and `ax.margins(x=0.01)` to remove some whitespace). Note that you shouldn't assign `ax` to the result of `ax = ax.bar(....)` as that will overwrite the `ax` variable. – JohanC Mar 27 '22 at 23:48
  • @JohanC thanks so much. great point about assigning ax to the result. not sure what I was thinking – dat.a.tho Mar 27 '22 at 23:53

0 Answers0