问题
I am generating a plot using matplot lib to plot many points (~a few thousand) by doing the following:
labels = []
for item in items:
label = item[0]
labels.append(label)
plt.plot(item[1][0], item[1][1], 'ro', c = colors[item], label = str(label))
And then generating a legend by doing:
plt.legend([str(x) for x in np.unique(labels)])
However, for each label in the legend the corresponding color is the same (not the color in the plot). Is there any way to manually set the color for the legend.
I have attached a sample plot to illustrate the problem.
--EDIT--
Just calling plt.legend()
as suggested by some does not seem to solve the problem for me, it adds a legend entry for each point. See the image below for an example output:
回答1:
This should work:
labels = []
for item in items:
label = item[0]
plt.plot(item[1][0], item[1][1], 'o', c=colors[item], label=str(label))
plt.legend()
If you specify the labels directly when creating the artist (in the call to plot
), you can just call plt.legend()
without arguments. It will iterate through the artists in the current axis and use their labels. That way the colors in the legend will match the ones in the plot.
回答2:
You could also create fake line markers and use them as legend entries:
markers = [plt.Line2D([0,0],[0,0], color=color[item], marker='o', linestyle='') for item in np.unique(items)]
plt.legend(markers, np.unique(labels), numpoints=1)
You can see a complete example in this answer.
Note that I have not tested this and you might need to adjust np.unique(items)
to your actual data set. color
is assumed to be a dictionary with colors for your items.
来源:https://stackoverflow.com/questions/31407207/matplotlib-set-color-of-legend