matplotlib 设置图例颜色 [英] matplotlib set color of legend

查看:221
本文介绍了matplotlib 设置图例颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 matplot lib 生成一个图,通过执行以下操作来绘制多个点(约几千个):

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.

-编辑-仅仅按照某些人的建议调用 plt.legend()似乎并不能解决我的问题,它为每个点添加了一个图例条目.有关示例输出,请参见下图:

--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:

推荐答案

这应该有效:

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()

如果在创建艺术家时直接指定标签(在对 plot 的调用中),则可以直接调用不带参数的 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.

这篇关于matplotlib 设置图例颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆