对于单个或堆叠的条形图,我可以通过使用来根据值改变颜色强度sns.color_palette("Blues", len(df['x']))
(它有自己的问题,等效条仍然具有不同的颜色,但这是以后的问题)。看起来像这样 -
现在我希望在catplot中做同样的事情。浏览文档看起来palette
应该会有所帮助,所以我构建了我的调色板,如下所示 -
palette={'A': sns.color_palette("Blues", 51), 'B': sns.color_palette('Reds', 51), 'C': sns.color_palette('Greens', 51)}
其中A
, B
,C
是 3 个不同的类别,其中颜色强度应根据其在 y 轴上的值而改变。我硬编码了类别的长度以获得快速解决方案。然而,这不起作用并且没有生成调色板 -
错误 -
ValueError: Could not generate a palette for <map object at 0x7efc31a60358>
用于测试您的代码的示例数据 -
index category value
0 1/22/20 A 30
1 1/23/20 A 20
2 1/24/20 A 20
3 1/25/20 B 5
4 1/26/20 B 10
5 1/27/20 B 15
6 1/28/20 C 2
7 1/29/20 C 5
8 1/30/20 C 7
相同的代码 -
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.DataFrame({'index':['1/22/20', '1/23/20', '1/24/20', '1/22/20', '1/23/20', '1/24/20', '1/22/20', '1/23/20', '1/24/20'], 'category': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'], 'value': [30,20,20,5,10,15,2,5,7]})
p = {'A': sns.color_palette("Blues", 3), 'B': sns.color_palette('Reds', 3), 'C': sns.color_palette('Greens', 3)}
sns.catplot(x='index', y='value', hue='category', data=df, kind='bar', palette=p)
plt.show()
使用 Matplotlib 的解决方案也很好。
编辑-
我认为归结为正确定义调色板。我想这就是你定义它的方式——
p = {'A': sns.color_palette("Blues", 3), 'B': sns.color_palette('Reds', 3), 'C': sns.color_palette('Greens', 3)}
其中键是category
.
现有代码实际上又给出了一个我没有提到的错误 -
ValueError: Invalid RGBA argument:......
我尝试如下定义我的调色板,但我得到与上面相同的错误 -
n1 = plt.Normalize(a["A"].values.min(), a["A"].values.max())
n2 = plt.Normalize(b["B"].values.min(), b["B"].values.max())
n3 = plt.Normalize(c["C"].values.min(), c["C"].values.max())
c1 = plt.cm.Blues(n1(a["A"]))
c2 = plt.cm.Reds(n2(b["B"]))
c3 = plt.cm.Greens(n3(c["C"]))
p = {"A": c1, "B" : c2, "C": c3}
其中a
和是包含单个类别及其值的数据框b
。c
我在这里想念什么?