使用matplotlib 3.1.1中的legend_元素设置散点图图例标签

2024-05-15 13:05:19 发布

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

我刚刚将matplotlib升级到3.1.1版本,并尝试使用legend_元素。在

我正在制作一个散乱图,从PCA的前两个组成部分的数据集30000平坦,灰度图像。每个图片都被标记为四个主要类别之一(配饰、服装、鞋类、个人护理)。我通过创建一个值从0到3的颜色列,按“主类别”对绘图进行了颜色编码。在

我已经阅读了PathCollection.legend_元素,但我没有成功地合并'func'或'fmt'参数。 https://matplotlib.org/3.1.1/api/collections_api.html#matplotlib.collections.PathCollection.legend_elements

此外,我还尝试了以下示例: https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/scatter_with_legend.html

### create column for color codes
masterCat_codes = {'Accessories':0,'Apparel':1, 'Footwear':2, 'Personal Care':3}
df['colors'] = df['masterCategory'].apply(lambda x: masterCat_codes[x])

### create scatter plot
fig, ax = plt.subplots(figsize=(8,8))
scatter = ax.scatter( *full_pca.T, s=.1 , c=df['colors'], label= df['masterCategory'], cmap='viridis')

### using legend_elements
legend1 = ax.legend(*scatter.legend_elements(num=[0,1,2,3]), loc="upper left", title="Category Codes")
ax.add_artist(legend1)
plt.show()

生成的图例标签为0、1、2、3。(在定义“散点”时,无论是否指定label=df['masterCategory']都会发生这种情况)。我想标签上说配件,服装,鞋类,个人护理。在

有没有办法用legend_元素来实现这一点?在

注意:由于数据集很大,预处理的计算量很大,因此我写了一个更易于重现的示例:

^{pr2}$

Tags: 数据护理元素dfmatplotlib颜色elementsax
1条回答
网友
1楼 · 发布于 2024-05-15 13:05:19

解决方案感谢重要的Beingernest

group_codes = {k:idx for idx, k in enumerate(fake_df.Group.unique())}
fake_df['colors'] = fake_df['Group'].apply(lambda x: group_codes[x])
fig, ax = plt.subplots(figsize=(8,8))
ax.scatter(fake_data[:,0], fake_data[:,1], c=fake_df['colors'])
ax.legend(handles=scatter.legend_elements(num=[0,1,2,3])[0], labels=group_codes.keys())
plt.show()

相关问题 更多 >