gpt4 book ai didi

python - 从 Seaborn 调色板中选择颜色

转载 作者:行者123 更新时间:2023-12-04 01:48:34 26 4
gpt4 key购买 nike

我有五个并排的分布图,通常使用颜色属性更改每个分布图的颜色。但是,现在我想使用 Seaborn 的 husl 调色板,但我不知道如何将调色板中的颜色应用于每个图表。我很确定这只是我正在寻找的东西。

# sns.set(style="white", palette="muted", color_codes=True)  
sns.set(style="white", palette="husl", color_codes=True)

# Set up the matplotlib figure
f, axes = plt.subplots(ncols=5, figsize=(15, 4))
sns.despine(left=True)

# Rating of 1
sns.distplot(df1[df1['rating']==1]['cost'], kde=False, color='c', ax=axes[0], axlabel="Rating of 1")

# Rating of 2
sns.distplot(df1[df1['rating']==2]['cost'], kde=False, color='k', ax=axes[1], axlabel='Rating of 2')

# Rating of 3
sns.distplot(df1[df1['rating']==3]['cost'], kde=False, color="g", ax=axes[2], axlabel='Rating of 3')

# Rating of 4
sns.distplot(df1[df1['rating']==4]['cost'], kde=False, color="m", ax=axes[3], axlabel='Rating of 4')

# Rating of 5
sns.distplot(df1[df1['rating']==5]['cost'], kde=False, color="b", ax=axes[4], axlabel='Rating of 5')

plt.setp(axes, yticks=[])
plt.tight_layout()

最佳答案

Seaborn 通过 husl_palette 提供到 husl 空间的接口(interface).您可以创建一个调色板,其颜色与您拥有的独特类别一样多(此处为“评级”)。然后,索引调色板或对其进行迭代。后者如下图所示。

import matplotlib.pyplot as plt
import seaborn as sns; sns.set(style="white")
import pandas as pd
import numpy as np

df = pd.DataFrame({"cost" : np.random.randn(600),
"rating" : np.random.choice(np.arange(1,6), size=600)})

ratings = np.unique(df.rating.values)
palette = iter(sns.husl_palette(len(ratings)))

f, axes = plt.subplots(ncols=len(ratings), figsize=(15, 4))
sns.despine(left=True)

for (n, rat), ax in zip(df.groupby("rating"), axes):

sns.distplot(rat["cost"], kde=False, color=next(palette), ax=ax, axlabel=f"Rating of {n}")

plt.setp(axes, yticks=[])
plt.tight_layout()
plt.show()

enter image description here

关于python - 从 Seaborn 调色板中选择颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54336695/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com