定制Seaborn Barplot中使用的“Hue”颜色

6

我正在使用seaborn创建以下图表:

enter image description here

我想自定义由hue生成的颜色,最好将颜色的顺序设置为蓝色、绿色、黄色、红色。 我已经尝试将颜色或颜色列表传递给sns.barplot中的color参数,但是它会产生渐变的颜色或者错误。

请指教。

您可以使用以下代码重现此图表:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

df = pd.DataFrame({'Early': {'A': 686, 'B': 533, 'C': 833, 'D': 625, 'E': 820},
 'Long Overdue': {'A': 203, 'B': 237, 'C': 436, 'D': 458, 'E': 408},
 'On Time': {'A': 881, 'B': 903, 'C': 100, 'D': 53, 'E': 50},
 'Overdue': {'A': 412, 'B': 509, 'C': 813, 'D': 1046, 'E': 904}})

df_long = df.unstack().to_frame(name='value')
df_long = df_long.swaplevel()
df_long.reset_index(inplace=True)
df_long.columns = ['group', 'status', 'value']
df_long['status'] = pd.Categorical(df_long['status'], ["Early", "On Time", "Overdue", "Long Overdue"])
df_long = df_long.sort_values("status")

fig, ax = plt.subplots(figsize=(18.5, 10.5))

g = sns.barplot(data=df_long, x='group', y='value', hue='status', ax=ax)

for bar in g.patches:
    height = bar.get_height()
    ax.text(bar.get_x() + bar.get_width() / 2., 0.5 * height, int(height),
                ha='center', va='center', color='white')
plt.xticks(fontsize=12)
plt.legend(loc='upper left', prop={'size': 14})

ax.xaxis.label.set_visible(False)
ax.axes.get_yaxis().set_visible(False)
plt.show()
1个回答

11

seaborn.barplot()中的hue变量通过palette进行映射:

palette: 调色板名称、列表或字典

用于不同hue变量级别的颜色。应该是可以被seaborn.color_palette()解释的内容,或者是将hue级别映射到matplotlib颜色的字典。

因此,要自定义您的hue颜色,

  • either define a color list:

    palette = ['tab:blue', 'tab:green', 'tab:orange', 'tab:red']
    
  • or a hue-color dictionary:

    palette = {
        'Early': 'tab:blue',
        'On Time': 'tab:green',
        'Overdue': 'tab:orange',
        'Long Overdue': 'tab:red',
    }
    
将其传递给palette:
sns.barplot(data=df_long, x='group', y='value', hue='status',
    palette=palette, ax=ax)

barplot with custom palette


3
你不需要显式地调用 color_palette;只需将颜色列表传递给 palette 即可。 - mwaskom
你能否使用同样的方法传递十六进制颜色代码? - gernworm
2
我建议也传递saturation=1参数:https://stackoverflow.com/questions/56062793/inconsistent-colours-from-custom-seaborn-palette - user357269

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接