按类别更改散点图中的颜色

2024-10-01 09:16:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何在下的python代码中手动更改类别的颜色,而不是使用cmap

我想要的颜色是以下十六进制颜色代码:

蓝色:#1f77b4

橙色:#ff7f0e

绿色:#2ca02c

红色:#d62728

d = """category1,05-01-2020 category1,02-02-2020 category3,06-03-2020 category2,12-04-2020 category4,07-05-2020 """ df = pd.read_csv(StringIO(d), sep=',', parse_dates=[1], header=None, names=['category','date']) fig, ax = plt.subplots() ax.scatter(df['date'],df['category'], marker='s', c=df['category'].astype('category').cat.codes, cmap='tab10')

谢谢你的帮助


Tags: 代码dfdate颜色手动ax类别橙色
1条回答
网友
1楼 · 发布于 2024-10-01 09:16:10

感谢您提供示例数据
Seabornhuepalette关键字参数,这使得这个过程非常简单

import seaborn as sns

df = df.sort_values('category')
sns.scatterplot('date','category',marker='s',data=df,
                hue='category',palette=['#1f77b4','#ff7f0e','#2ca02c','#d62728'])
plt.gcf().autofmt_xdate()
plt.show()

结果:
enter image description here


如果您想继续使用vanilla Matplotlib,可以执行以下操作:

from matplotlib.colors import LinearSegmentedColormap

cmap = LinearSegmentedColormap.from_list('custom_colors',
                                         ['#1f77b4','#ff7f0e','#2ca02c','#d62728'])

fig, ax = plt.subplots() 
ax.scatter(df['date'],df['category'], marker='s', 
           c=df['category'].astype('category').cat.codes, cmap=cmap)

相关问题 更多 >