2017-02-07 41 views
0

我曾在下述方式來構成散點圖情節:添加傳說撒在Python

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保存的數據和y持有的標籤(1,2,3)。現在我想添加一個圖例。

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

這不起作用,它只打印label1。這怎麼能做到呢?

回答

1

這個想法是將數據集劃分在由相同顏色表示的單獨數據集上。之後,圖例正確顯示。

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

enter image description here