Matplotlib散点图图例 [英] Matplotlib Scatterplot legend for points

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

问题描述

我正在以编程方式创建这样的散点图:

I am programmatically creating a scatterplot like this:

(Ipython sample code)
%matplotlib inline
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, axisbg="1.0")
d1 = [range(1,11)]
d2 = [range(1,11)]
dcolor = ['red','red','red','green','green','green','blue','blue','blue', 'blue']
colordict{'red': 'monkey', 'green':'whale', 'blue':'cat'}
ax.scatter(d1,d2,alpha=0.8, c=dcolor,edgecolors='none',s=30)

我想为每个不同的点添加一个图例,以便图例包含一个给定颜色的点和来自 colordict 的名称.如果不将散点图的创建拆分为多个对 scatter 的调用,这可能吗?由于这发生在自动化库中,我宁愿避免对 scatter() 进行不同的调用.

I would like to add a legend for each different point, so that the legend contains a point in the given color and the name from colordict. Is that possible without splitting the creation of the scatterplot into multiple calls to scatter? Since this happens in a automated library, I would rather avoid to have different calls to scatter().

推荐答案

我可能会执行以下操作.

I would probably do the following.

%matplotlib inline
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, axisbg="1.0")

g1 = ([1,2,3], [1,2,3])
g2 = ([4,5,6], [4,5,6])
g3 = ([7,8,9,10], [7,8,9,10])
data = (g1, g2, g3)
colors = ("red", "green", "blue")
groups = ("monkey", "whale", "cat") 

for data, color, group in zip(data, colors, groups):
    x, y = data
    ax.scatter(x, y, alpha=0.8, c=color, edgecolors='none', s=30, label=group)
plt.legend(loc=2)

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

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