python - 自定义 Seaborn Barplot 中使用的 'Hue' 颜色

标签 python matplotlib seaborn

这个问题在这里已经有了答案:





Seaborn - change bar colour according to hue name

(1 个回答)


27 天前关闭。




我正在使用 seaborn 创建以下图表:
enter image description here
我想自定义由 hue 生成的颜色,最好将颜色的顺序设置为蓝色、绿色、黄色、红色。
我尝试将颜色或颜色列表传递给 color参数在 sns.barplot但是它会产生颜色渐变或错误。
请指教。
您可以使用以下代码来重现图表:

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

最佳答案

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

palette: palette name, list, or dict

Colors to use for the different levels of the hue variable. Should be something that can be interpreted by seaborn.color_palette(), or a dictionary mapping hue levels to matplotlib colors.


所以要定制您的hue颜色,
  • 要么定义一个颜色列表:
    palette = ['tab:blue', 'tab:green', 'tab:orange', 'tab:red']
    
  • hue - 颜色字典:
    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

    关于python - 自定义 Seaborn Barplot 中使用的 'Hue' 颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68616781/

    相关文章:

    python - 使用日期时间对象进行绘图时出现类型错误

    python - matplotlib 1.4.2 与 Seaborn : line markers not functioning

    python - pandas.scatter_matrix 函数开始绘制模糊和损坏的图

    python - 用字典扩展数据框

    python - Python 3.10 的 Matplotlib 安装问题

    python - 强制所有 x 轴值在 Python 的散点图中进行比较

    python - 如何使用 Seaborn 绘制字符串类型 Numpy 数组?

    python - 如何创建具有多个子图的带状图

    python - numpy 中概率被忽略

    python - 如何从数据文件中读取指定间隔的行?