简体   繁体   English

在Python中将图例添加到散点图

[英]Adding legend to scatter plot in Python

I have made a scatter plot in the following way: 我通过以下方式绘制了散点图:

f, ax1 = plt.subplots(3,2)
cmap = matplotlib.cm.get_cmap('coolwarm')
ax1[0,1].scatter(data[:,0], data[:,1], c=y, s=20, marker='o', alpha=.5, cmap=cmap)

data holds the data and y holds the labels (1,2,3). data保存数据, y保存标签(1,2,3)。 Now I would like to add a legend. 现在,我想添加一个图例。

ax1[0,1].legend(('label1', 'label2', 'label3'),
           scatterpoints=1,
           loc='lower left',
           fontsize=10)

This does not work, it only prints label1. 这是行不通的,它只打印label1。 How can this be done otherwise? 否则怎么办?

The idea is to divide data set on separate data sets which are represented by the same color. 想法是将数据集划分为用相同颜色表示的单独数据集。 After that the legend displayed properly. 之后,图例将正确显示。

import matplotlib.pyplot as plt
import matplotlib
import numpy as np

data = np.zeros(shape=(10,2))
data[:,0] = np.linspace(0,1,10)
data[:,1] = np.linspace(0,1,10)

y = ['red', 'green', 'blue']
f, ax1 = plt.subplots(3,2)
cmap = matplotlib.cm.get_cmap('coolwarm')
ny = len(y)
for i, itm in enumerate(y):
    datac = data[i::ny,:]
    ax1[0,1].scatter(datac[:,0], datac[:,1], c=itm, 
                     s=20, marker='o', alpha=.5, cmap=cmap)

ax1[0,1].legend(['label1', 'label2', 'label3'],
           scatterpoints=1,
           loc='lower left',
           fontsize=10)
plt.show()

在此处输入图片说明

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

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