I am creating a group of barplots using seaborn.FacetGrid. I'd also like to color in the n highest bars of each of these subplots. How do I do that? The code below generates regular subplots of bar graphs.
import seaborn as sns
import numpy as np
np.random.seed(0)
df = pd.DataFrame({'Category': ['A','B', 'C'], 'Variable A': np.random.choice(5,3), 'Variable B':np.random.choice(5,3), 'Variable C': np.random.choice(5,3)})
g = sns.FacetGrid(df.melt(id_vars = 'Category'), col = 'Category', col_wrap = 1, height =1.7, aspect =5)
g.map(sns.barplot,'variable','value')
In this example, how would I color the two highest bars per subplot in a different color (eg orange) than the rest (eg blue)?
I would argue that, if you want an output that's more customizable than what seaborn allows, you're probably better off not using seaborn at all and doing the plot directly using matplotlib's functions...
But anyway, here's a solution that works for your test scenario:
np.random.seed(0)
df = pd.DataFrame({'Category': ['A','B', 'C'], 'Variable A': np.random.choice(5,3), 'Variable B':np.random.choice(5,3), 'Variable C': np.random.choice(5,3)})
g = sns.FacetGrid(df.melt(id_vars = 'Category'), col = 'Category', col_wrap = 1, height =1.7, aspect =5)
g.map(sns.barplot,'variable','value')
top_N = 2
color = 'orange'
for ax in g.axes:
heights = [p.get_height() for p in ax.patches]
top = np.argsort(heights)[-top_N:]
for p in [ax.patches[i] for i in top]:
p.set_facecolor(color)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.