Python 更改Seaborn应用调色板的轴
我试图使用Seaborn将1d数据帧表示为水平条形图。我想用coolwarm调色板对这些条进行着色,以反映它们的大小和方向 换句话说,我希望生成类似于此处显示的第二个示例的内容(这来自),但我希望将其水平定向: 我已经成功地将图形侧向旋转,但我似乎无法使调色板也沿水平轴应用。我的代码:Python 更改Seaborn应用调色板的轴,python,pandas,seaborn,Python,Pandas,Seaborn,我试图使用Seaborn将1d数据帧表示为水平条形图。我想用coolwarm调色板对这些条进行着色,以反映它们的大小和方向 换句话说,我希望生成类似于此处显示的第二个示例的内容(这来自),但我希望将其水平定向: 我已经成功地将图形侧向旋转,但我似乎无法使调色板也沿水平轴应用。我的代码: import pandas as pd, seaborn as sns sns.set() df = pd.DataFrame([7,-5,-2,1.5,-3], inde
import pandas as pd, seaborn as sns
sns.set()
df = pd.DataFrame([7,-5,-2,1.5,-3],
index=['question 1','question 2','question 3','question 4','question 5'],
columns=['t'])
sns.barplot(data= df,
x= 't',
y= df.index,
palette= 'coolwarm')
输出:
我希望它在从左到右(而不是从上到下)移动时从蓝色变为红色。如果您不介意按增加值的顺序提问,可以执行以下操作:
df2 = df.sort_values('t')
sns.barplot(data=df2,
x='t',
y=df2.index
palette='coolwarm_r')
这将产生:
如果您想将问题保留为原始顺序,可以使用调色板
kwarg为sns.barplot
指定自定义调色板(RGBA值列表):
val_order = df['t'].rank(method='max').astype(int) # rank ordered values in column 't'
val_index = val_order - 1 # convert for use as a list index
colors = sns.color_palette('coolwarm_r', len(df.index)) # list of N colors spaced along coolwarm
palette = [colors[x] for x in val_index] # re-order colors with increasing value of 't'
sns.barplot(data=df, x='t', y=df.index, palette=palette)
屈服:
制作完这些图像后,我意识到我无意中使用了
coolwarm\u r
而不是coolwarm
。添加\u r
后缀将使用反向颜色映射。哦,好吧。Seaborn不执行任何真正的颜色映射。因此,如果这一点被取消,就需要从外部进行。在下面的示例中,每个条根据其大小从colormap获取其颜色
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
sns.set()
df = pd.DataFrame([7,-5,-2,1.5,-3],
index=['question 1','question 2','question 3','question 4','question 5'],
columns=['t'])
absmax = np.abs(df["t"].values).max()
norm = plt.Normalize(-absmax, absmax)
cmap = plt.get_cmap("coolwarm")
colors = cmap(norm(df["t"].values))
plt.barh("index", "t", data=df.reset_index(), color=colors)
plt.colorbar(plt.cm.ScalarMappable(norm, cmap))
plt.gca().invert_yaxis()
plt.tight_layout()
plt.show()
这将是一个非常晚的答复,但是 最简单的方法是将
hue
参数设置为要设置为着色轴的列:
sns.barplot(data=df,x='t',y=df.index,palette='coolwarm', hue='t', dodge=False)
将dodge
设置为True
非常重要,因为否则会得到非常细的线条状方框
您将得到这种输出:
谢谢!然而,在这两种解决方案中,颜色的阴影似乎对应于项目在排序中的位置,而不是其实际大小。由于我的实际数据并非如此均匀分布,我希望颜色的阴影能够反映它们的大小(例如,问题3和问题4都应该或多或少显示为灰色)。第二个选项根据列
't'
中的值选择颜色。您也可以使用数据帧中的任何其他列,例如,指定一个幅值列,并使用该列选择颜色:df.assign(幅值=λx:abs(x['t']))
您确定吗?在玩了一段时间之后,它看起来真的像是根据排名的t值而不是t值本身来选择颜色。请注意,行colors=sns.color\u调色板('coolwarm\u r',len(df.index))
生成一个等距颜色列表,然后在下一行中按列表方式分配给调色板。我明白你的意思。你说得对。在这种情况下,我认为可以使用a生成传递到调色板的RGBA值。还有,这正是我要找的。谢谢你的回复。