散点图的pyplot图例按值着色

时间:2016-07-04 20:18:55

标签: python matplotlib

当我使用变量为散点图着色时,如何制作说明颜色代表的图例?如何让图例显示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()

1 个答案:

答案 0 :(得分:2)

尝试使用此代码:

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

这就是你得到的:

enter image description here

要使用与图中所示颜色或标签不同的颜色或标签,您只需要相应地更改字典key的值。