由网友(承诺就像写在沙滩上的字)分享简介:我刚刚将matplotlib升级到版本3.1.1,我正在尝试使用LENGING_ELEMENTS。我在一个包含30,000个平面化灰度图像的数据集上绘制了来自PCA的前两个分量的散点图。每个图像都被标记为四个主要类别之一(配饰、服装、鞋类、个人护理)。我已经通过创建一个值从0到3的颜色列,通过‘主类别’对绘图进行了颜...
我刚刚将matplotlib升级到版本3.1.1,我正在尝试使用LENGING_ELEMENTS。
我在一个包含30,000个平面化灰度图像的数据集上绘制了来自PCA的前两个分量的散点图。每个图像都被标记为四个主要类别之一(配饰、服装、鞋类、个人护理)。我已经通过创建一个值从0到3的颜色列,通过‘主类别’对绘图进行了颜色编码。
我已经阅读了PathCollection.Legend_Elements的文档,但尚未成功合并‘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[‘master Category’],都会发生这种情况)。我希望标签上写着配件、服装、鞋类、个人护理。
有没有办法通过LENGING_ELEMENTS实现这一点?
注意:由于数据集很大,并且预处理的计算量很大,我写了一个更容易重现的示例:
fake_data = np.array([[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]])
fake_df = pd.DataFrame(fake_data, columns=['X', 'Y'])
groups = np.array(['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'])
fake_df['Group'] = groups
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()
scatter = ax.scatter(fake_data[:,0], fake_data[:,1], c=fake_df['colors'])
legend = ax.legend(*scatter.legend_elements(num=[0,1,2]), loc="upper left", title="Group
Codes")
ax.add_artist(legend)
plt.show()
推荐答案
解决方案 感谢ImportanceOfBeingErnest
.legend_elements
返回PathCollection
的图例句柄和标签。
handles = scatter.legend_elements(num=[0,1,2,3])[0]
,因为句柄是该方法返回的第一个对象。
另见Scatter plots with a legend
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))
scatter = ax.scatter(fake_data[:,0], fake_data[:,1], c=fake_df['colors'])
handles = scatter.legend_elements(num=[0,1,2,3])[0] # extract the handles from the existing scatter plot
ax.legend(title='Group
Codes', handles=handles, labels=group_codes.keys())
plt.show()
相关推荐
最新文章