2017-05-24 22 views
1

假設我的數據是通過以下方式進行組織:設置一個傳奇匹配pyplot.scatter顏色

x_values = [6.2, 3.6, 7.3, 3.2, 2.7] 
y_values = [1.5, 3.2, 5.4, 3.1, 2.8] 
colours = [1, 1, 0, 1, -1] 
labels = ["a", "a", "b", "a", "c"] 

我想和這個散點圖:

axis = plt.gca() 
axis.scatter(x_values, y_values, c=colours) 

我希望有一個傳說有3個類別:「a」,「b」和「c」。

如果此列表中的類別與colours列表中的點的順序相匹配,我可以使用labels列表來製作此圖例嗎?

是否需要爲每個類別分別運行scatter命令?

回答

1

如果你想使用一個顏色表,你可以爲每個一個圖例項如下所示的colors列表中的唯一條目。這種方法適用於任何數量的值。圖例句柄是plot的標記,以便它們與散點相匹配。

import matplotlib.pyplot as plt 

x_values = [6.2, 3.6, 7.3, 3.2, 2.7] 
y_values = [1.5, 3.2, 5.4, 3.1, 2.8] 
colors = [1, 1, 0, 1, -1] 
labels = ["a", "a", "b", "a", "c"] 
clset = set(zip(colors, labels)) 

ax = plt.gca() 
sc = ax.scatter(x_values, y_values, c=colors, cmap="brg") 

handles = [plt.plot([],color=sc.get_cmap()(sc.norm(c)),ls="", marker="o")[0] for c,l in clset ] 
labels = [l for c,l in clset] 
ax.legend(handles, labels) 

plt.show() 

enter image description here

+0

爲什麼需要手動使用此規範化來設置'plot'中的顏色? 「scatter」和「plot」中的顏色確定機制是否相同? 這是幾年來我偶爾使用matplotlib,我一直困惑。 – bli

+1

你有一個'scatter',但有三個'plot's。因此,雖然分散會知道正常化,但每個個體都不知道它。但是您是正確的,因爲我們不需要手動設置規範化,但可以重新使用分散規範化。我相應地更新了答案。 – ImportanceOfBeingErnest

0

您可以隨時在自己的圖例如下:

import matplotlib.pyplot as plt 
import matplotlib.patches as mpatches 

x_values = [6.2, 3.6, 7.3, 3.2, 2.7] 
y_values = [1.5, 3.2, 5.4, 3.1, 2.8] 

a = 'red' 
b = 'blue' 
c = 'yellow' 

colours = [a, a, b, a, c] 
labels = ["a", "a", "b", "a", "c"] 

axis = plt.gca() 
axis.scatter(x_values, y_values, c=colours) 

# Create a legend 
handles = [mpatches.Patch(color=colour, label=label) for label, colour in [('a', a), ('b', b), ('c', c)]] 
plt.legend(handles=handles, loc=2, frameon=True) 

plt.show() 

這將是這樣的:

plot with legend

+0

我試圖理解你的答案,但無法找到plt.legend'的'的幫助下,「把手」的關鍵字。它是如何工作的?我想,在這種情況下,「句柄」是繪製圖例條目圖形部分的東西(幫助稱爲「傳奇藝術家」)。我對麼 ? – bli

+0

相當多的matplotlib函數將任何未知的關鍵字傳遞給子函數來處理,但是這[link](http://matplotlib.org/users/legend_guide.html#creating-artists-specifically-for-adding這對傳奇又名代理藝術家)應該有所幫助。 –