如何为seaborn barplot中最大的酒吧设置不同的颜色?

pmd*_*aly 10 python bar-chart seaborn

我正在尝试创建一个条形图,其中所有小于最大的条形都是一些淡淡的颜色,最大的条形是更鲜明的颜色.一个很好的例子是黑马分析饼图gif,它们分解饼图并以更清晰的条形图结束.任何帮助将不胜感激,谢谢!

iay*_*ork 23

只需传递颜色列表即可.就像是

values = np.array([2,5,3,6,4,7,1])   
idx = np.array(list('abcdefg')) 
clrs = ['grey' if (x < max(values)) else 'red' for x in values ]
sb.barplot(x=idx, y=values, palette=clrs) # color=clrs)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

(正如评论中所指出的,Seaborn的后续版本使用"调色板"而不是"颜色")

  • 在当前版本中,`color =`关键字必须替换为`palette =` (5认同)

Nic*_*ico 9

其他答案绘图之前定义了颜色。您可以也做到这一点之后通过改变自己吧,这是你用来为情节线的补丁。要重新创建 iayork 的示例:

import seaborn
import numpy

values = numpy.array([2,5,3,6,4,7,1])   
idx = numpy.array(list('abcdefg')) 

ax = seaborn.barplot(x=idx, y=values) # or use ax=your_axis_object

for bar in ax.patches:
    if bar.get_height() > 6:
        bar.set_color('red')    
    else:
        bar.set_color('grey')
Run Code Online (Sandbox Code Playgroud)

您也可以直接通过例如ax.patches[7]. 有了dir(ax.patches[7])可以显示条对象,你可以利用的其他属性。


Muh*_*zan 6

[Barplot case]如果您从数据框中获取数据,则可以执行以下操作:

labels = np.array(df.Name)
values = np.array(df.Score) 
clrs = ['grey' if (x < max(values)) else 'green' for x in values ]
#Configure the size
plt.figure(figsize=(10,5))
#barplot
sns.barplot(x=labels, y=values, palette=clrs) # color=clrs)
#Rotate x-labels 
plt.xticks(rotation=40)
Run Code Online (Sandbox Code Playgroud)