[英]How does one plot the legend with pyplot.scatter(), when the legend are only numerical values?
[英]pyplot legend for scatter plot colored by values
当我使用变量为散点图着色时,如何制作图例说明什么颜色表示? 如何使图例显示标签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()
试试下面的代码:
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()
这就是您将得到的:
要使用不同于图中所示的颜色或标签,您只需要适当地更改字典key
的值即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.