2011-02-28 68 views
190

我想在matplotlib中做一個散點圖,但我找不到向點添加標記的方法。例如:如何爲散點圖添加單個標記

scatter1=plt.scatter(data1["x"], data1["y"], marker="o", 
        c="blue", 
        facecolors="white", 
        edgecolors="blue") 

我想爲「Y」的點有標籤爲「點1」,「2點」,等等。我無法弄清楚。

回答

330

也許使用plt.annotate

import numpy as np 
import matplotlib.pyplot as plt 

N = 10 
data = np.random.random((N, 4)) 
labels = ['point{0}'.format(i) for i in range(N)] 

plt.subplots_adjust(bottom = 0.1) 
plt.scatter(
    data[:, 0], data[:, 1], marker='o', c=data[:, 2], s=data[:, 3] * 1500, 
    cmap=plt.get_cmap('Spectral')) 

for label, x, y in zip(labels, data[:, 0], data[:, 1]): 
    plt.annotate(
     label, 
     xy=(x, y), xytext=(-20, 20), 
     textcoords='offset points', ha='right', va='bottom', 
     bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5), 
     arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0')) 

plt.show() 

enter image description here

+7

這就是我要說的。鏈接到文檔:http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.annotate鏈接到演示:http://matplotlib.sourceforge.net/examples/pylab_examples/annotation_demo2.html – Paul 2011-02-28 21:06:38

+0

非常好!它像一個魅力。 – 2011-02-28 21:12:49

+3

@ubuntu是否有可能使用數字(或標籤)_index of the points? – Vladtn 2012-02-29 13:40:31