python - 将图例添加到散点图

标签 python matplotlib legend scatter-plot

SO上有人问过这个问题,但我想找到一个更清晰的解决方案。

给定 X 是 100x2 数据,labels 是标签向量(从 1 到 9),我绘制散点图如下:

pl.scatter(X[:,0], X[:,1], c = labels)
pl.show()

enter image description here

如何在一行代码中添加图例来解释颜色?其他解决方案分别绘制每个标签:

a = pl.scatter(X1[:,0], X1[:,1], color = "red")
b = pl.scatter(X2[:,0], X2[:,1], color = "green")
c = pl.scatter(X3[:,0], X3[:,1], color = "blue")
pl.legend((a,b,c), ("line 1", "line 2", "line 3")
pl.show()

最佳答案

您可以创建一个带有所需图例的虚拟散点图,如下所示:

pl.scatter(X[:,0], X[:,1], c = labels)

for item in labels:
    #dummy plot just to create the legend
    pl.scatter([], [], c = item, label = item)
#loc = 0 is for the best position of the legend
#scatterpoints = 1 will only show one point in the legend instead of multiple points
plt.legend(loc = 0, scatterpoints = 1)
pl.show()

关于python - 将图例添加到散点图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23094774/

相关文章:

python - LeetCode "Paint House"问题 : time limit exceeded despite O(N) solution?

python - Matplotlib:用户定义的绘图函数打印两次

python - Matplotlib 添加基于现有颜色系列的图例

python - 为什么无法在图例旁边进行注释?

python - python 中的 "if var and var2 == getSomeValue()"- 如果第一个为假,是否评估第二个语句?

python - python 解析器库中的月份和日期交换

python - groupby 和过滤 Pandas

python - matplotlib 中的 Latex 脚本

Matplotlib set_major_formatter 属性错误

javascript - Highcharts:在图例中显示堆叠图表的最后一个值