简体   繁体   English

Seaborn 子图为 n 个最高条提供不同颜色

[英]Seaborn subplots give n highest bars different color

I am creating a group of barplots using seaborn.FacetGrid.我正在使用 seaborn.FacetGrid 创建一组条形图。 I'd also like to color in the n highest bars of each of these subplots.我还想为每个子图的 n 个最高条着色。 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...我认为,如果你想要一个比 seaborn 允许的更可定制的输出,你可能最好根本不使用 seaborn 并直接使用 matplotlib 的函数进行绘图......

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)

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM