带图例的matplotlib散点图 [英] matplotlib scatterplot with legend

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

问题描述

我对在散点图中绘制图例感兴趣.我当前的代码如下:

I am interested in plotting a legend in my scatterplot. My current code looks like this

x=[1,2,3,4]
y=[5,6,7,8]
classes = [2,4,4,2]
plt.scatter(x, y, c=classes, label=classes)
plt.legend()

问题在于创建图时,图例显示为数组,而不是显示唯一标签及其类.

The problem is that when the plot is created, the legend is shown as an array instead of showing the unique labels and their classes.

我知道这是先前在诸如 one 之类的线程中讨论的一个问题. ,但是我觉得我的问题甚至更简单,那里的解决方案不适合它.同样,在该示例中,人员指定了颜色,但就我而言,我事先知道我需要多少种颜色.此外,在示例中,用户正在创建多个散布,每个散布具有唯一的颜色.同样,这不是我想要的.我的目标是使用x,y数组和标签简单地创建图.这可能吗?

I am aware this is a question discussed previously in threads such as this one, however I feel that my problem is even simpler and the solution there does not fits it. Also, in that example the person is specifying the colors however in my case I do know beforehand how many colors I'll need. Moreover, in this example the user is creating multiple scatters, each one with a unique color. Again, this is not what I want. My goal is to simply create the plot using an x,y array and the labels. Is this possible?

谢谢.

推荐答案

实际上,两个链接的问题都提供了一种方法来实现所需的结果.

Actually both linked questions provide a way how to achieve the desired result.

最简单的方法是创建与存在的唯一类一样多的散点图,并为每个散点图指定一个颜色和图例条目.

The easiest method is to create as many scatter plots as unique classes exist and give each a single color and legend entry.

import matplotlib.pyplot as plt

x=[1,2,3,4]
y=[5,6,7,8]
classes = [2,4,4,2]
unique = list(set(classes))
colors = [plt.cm.jet(float(i)/max(unique)) for i in unique]
for i, u in enumerate(unique):
    xi = [x[j] for j  in range(len(x)) if classes[j] == u]
    yi = [y[j] for j  in range(len(x)) if classes[j] == u]
    plt.scatter(xi, yi, c=colors[i], label=str(u))
plt.legend()

plt.show()

如果类是字符串标签,则解决方案看起来会稍有不同,因为您需要从它们的索引中获取颜色,而不是使用类本身.

In case the classes are string labels, the solution would look slightly different, in that you need to get the colors from their index instead of using the classes themselves.

import numpy as np
import matplotlib.pyplot as plt

x=[1,2,3,4]
y=[5,6,7,8]
classes = ['X','Y','Z','X']
unique = np.unique(classes)
colors = [plt.cm.jet(i/float(len(unique)-1)) for i in range(len(unique))]
for i, u in enumerate(unique):
    xi = [x[j] for j  in range(len(x)) if classes[j] == u]
    yi = [y[j] for j  in range(len(x)) if classes[j] == u]
    plt.scatter(xi, yi, c=colors[i], label=str(u))
plt.legend()

plt.show()

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

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