matplotlib set color of legend

吃可爱长大的小学妹 提交于 2021-02-19 03:51:49

问题


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. enter image description here

--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: enter image description here


回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!