繁体   English   中英

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

[英]Seaborn subplots give n highest bars different color

我正在使用 seaborn.FacetGrid 创建一组条形图。 我还想为每个子图的 n 个最高条着色。 我怎么做? 下面的代码生成条形图的常规子图。

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

在此处输入图片说明

在这个例子中,我如何将每个子图的两个最高条着色为与其他颜色(例如蓝色)不同的颜色(例如橙色)?

我认为,如果你想要一个比 seaborn 允许的更可定制的输出,你可能最好根本不使用 seaborn 并直接使用 matplotlib 的函数进行绘图......

但无论如何,这里有一个适用于您的测试场景的解决方案:

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