更改 seaborn 条形图中的色标 [英] Changing color scale in seaborn bar plot
问题描述
我想对我的数据使用 seaborn 条形图,并根据 Y 轴中的值使用色标.例如,从这张图片中,颜色根据调色板从左到右变化:
I would like to use seaborn bar plot for my data with a color scale according to the values in the Y-axis. For example, from this image, color changes from left to right according to a color palette:
但我真正想要的是相同的配色方案,但在垂直"而不是水平".这可能吗?我已经搜索并尝试将 hue
参数设置为 Y 轴,但它似乎不起作用,我该怎么做?
But what I actually wanted is this same color scheme but in "vertical" instead of "horizontal". Is this possible? I've searched and tried to set the hue
parameter to the Y-axis but it doesn't seem to work, how can I do it?
提前致谢.
推荐答案
这里有一个解决方案:
import numpy as np, matplotlib.pyplot as plt, seaborn as sns
sns.set(style="whitegrid", color_codes=True)
titanic = sns.load_dataset("titanic")
data = titanic.groupby("deck").size() # data underlying bar plot in question
pal = sns.color_palette("Greens_d", len(data))
rank = data.argsort().argsort() # http://stackoverflow.com/a/6266510/1628638
sns.barplot(x=data.index, y=data, palette=np.array(pal[::-1])[rank])
plt.show()
这里的输出:
注意:代码当前为相同高度的条形分配不同(相邻)颜色.(示例图中这不是问题.)虽然对相同高度的条使用相同颜色会更好,但生成的代码可能会使基本思想不那么清晰.
Note: the code currently assigns different (adjacent) colors to bars with identical height. (Not a problem in the sample plot.) While it would be nicer to use the same color for identical-height bars, the resulting code would likely make the basic idea less clear.
这篇关于更改 seaborn 条形图中的色标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!