2011-08-05 35 views
4

我在python中使用matplotlib庫來生成發佈質量的xy散點圖。我遇到了關於圖例中標記的問題。我正在繪製2個不同的xy-scatter系列;一個是形成曲線的一組xy點,另一個是單個xy點。Matplotlib圖例:如何分配多個散點值

我希望圖例顯示3個標記爲「曲線」,1個標記爲單點。我知道如何更改圖例標記的數量的唯一方法是在聲明圖例時使用「scatterpoints」參數。但是,該參數設置了圖例中所有系列的標記數量,並且我不確定如何更改每個圖例條目單獨的

很遺憾,我無法將照片作爲新用戶發佈,但希望此說明足夠。 有沒有辦法使用matplotlib爲每個圖例條目分別設置散點值?

編輯:這裏是鏈接顯示圖像與散點不同的值。

scatterpoints = 3:http://imgur.com/8ONAT

scatterpoints = 1:http://imgur.com/TFcYV

希望這使得問題有點更清晰。

+0

你要在三個「片段」分裂「曲線」,並使用不同的標記每個段?你想如何將標記分配給散點「曲線」的點? –

回答

4

你可以得到傳說中的行,自己去改變它:

import numpy as np 
import pylab as pl 
x = np.linspace(0, 2*np.pi, 100) 
pl.plot(x, np.sin(x), "-x", label=u"sin") 
pl.plot(x, np.random.standard_normal(len(x)), 'o', label=u"rand") 
leg = pl.legend(numpoints=3) 
l = leg.legendHandles[1] 
l._legmarker.set_xdata(l._legmarker.get_xdata()[1:2]) 
l._legmarker.set_ydata(l._legmarker.get_ydata()[1:2]) 
##or 
#l._legmarker.set_markevery(3) 
pl.show() 

Legend.legendHandles是傳說中的所有行的列表,以及該行的_legmarker屬性標記。

您可以調用set_markevery(3)或set_xdata()& set_ydata()更改標記數。

enter image description here

+0

這個答案對我很好,謝謝。我將添加一個警告:對於由pyplot.plot()生成的Line2D集合存在_legmarker屬性,但對於由pyplot.scatter()生成的RegularPolyCollection集合不存在。這在我的情況下是可以的,因爲我只是將我需要繪製的單個點從plt.scatter()轉換爲plt.plot()。 –