I want to change the color of a bar in matplotlib's grouped barplot if it meets a certain condition. I'm plotting two bars for each species - one for today and one for avg, where avg contains yerr errorbars that show the 10th and 90th percentile values.
Now I want the avg bar to be green if today's length value > 10th percentile, and red if today's length value < 10th percentile.
I tried the solutions in these posts
CodePudding user response:
One way is to overwrite the colors after creating the plot. First you need to change the line that initialize
colwithcol = ['pink']*z['species'].nunique()to get the numbers of avg bars, then the same for loop to add g or r depending on your case. Finally, change this
fig, ax = plt.subplots() z0.pivot(index='species', columns='type', values='length')\ .plot(kind='bar', yerr=bars, ax=ax, color=['pink','g'], capsize=0) # here use only pink and g # here overwrite the colors for p, c in zip(ax.patches, col): p.set_color(c) ax.set_title...Note that the legend for today is green even if you have a red bar, could be confusing.
Here is the full working example, adding the red entry in the legend thanks to

