这个问题在这里已经有了答案:
Seaborn - change bar colour according to hue name
(1 个回答)
27 天前关闭。
我正在使用 seaborn 创建以下图表:
我想自定义由 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 byseaborn.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)
关于python - 自定义 Seaborn Barplot 中使用的 'Hue' 颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68616781/