简体   繁体   English

散点图的pyplot图例以值着色

[英]pyplot legend for scatter plot colored by values

When I use a variable for coloring a scatter plot, how can I make a legend stating what colors represent? 当我使用变量为散点图着色时,如何制作图例说明什么颜色表示? How can I make the legend show a label of 0 represents empty and 1 represents full? 如何使图例显示标签0表示空,而1表示已满?

import matplotlib.pyplot as plt
X = [1,2,3,1,2,3,4]
Y = [1,1,1,2,2,2,2]
label = [0,1,1,0,0,1,1]
plt.scatter(X, Y, c= label, s=50)
plt.show()

Give this code a try: 试试下面的代码:

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
X = [1, 2 ,3, 1, 2, 3, 4]
Y = [1, 1, 1, 2, 2, 2, 2]
labels = [0, 1, 1, 0, 0, 1, 1]
key = {0: ('red', 'empty'), 1: ('green', 'full')}
plt.scatter(X, Y, c=[key[index][0] for index in labels], s=50)
patches = [mpatches.Patch(color=color, label=label) for color, label in key.values()]
plt.legend(handles=patches, labels=[label for _, label in key.values()], bbox_to_anchor=(1, .3))
plt.show()

And this is what you'll get: 这就是您将得到的:

在此处输入图片说明

To use colors or labels different than those shown in the figure you simply need to change the values of the dictionary key appropriately. 要使用不同于图中所示的颜色或标签,您只需要适当地更改字典key的值即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM