Set Scatter Plot Legend Labels With Legend_elements
I just upgraded matplotlib to version 3.1.1 and I am experimenting with using legend_elements. I am making a scatterplot of the top two components from PCA on a dataset of 30,000 f
Solution 1:
Solution Thanks to ImportanceOfBeingErnest
.legend_elements
returns legend handles and labels for aPathCollection
.handles = scatter.legend_elements(num=[0,1,2,3])[0]
because the handles are the first object returned by the method.
- Also see 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\nCodes', handles=handles, labels=group_codes.keys())
plt.show()
Post a Comment for "Set Scatter Plot Legend Labels With Legend_elements"