傳說

2014-05-16 53 views
16

點的手動設置顏色我正在做散點圖,看起來像這樣:傳說

enter image description here

(在問題的底部MWE)

正如上面圖片中可以看出通過matplotlib,圖例中點的顏色自動設置爲藍色。我需要將這些點設置爲顏色映射中不存在的其他顏色(即:黑色),以免它們與所述顏色映射關聯的顏色混淆。

我環顧四周,但matplotlib.legend模塊似乎並不接受color關鍵字。有沒有辦法做到這一點?


這裏的MWE:

import matplotlib.pyplot as plt 
import numpy as np 

def rand_data(): 
    return np.random.uniform(low=0., high=1., size=(100,)) 

# Generate data. 
x, y, x2, x3 = [rand_data() for i in range(4)] 
# This data defines the markes and labels used. 
x1 = np.random.random_integers(7, 9, size=(100,)) 

# Order all lists so smaller points are on top. 
order = np.argsort(-np.array(x2)) 
# Order x and y. 
x_o, y_o = np.take(x, order), np.take(y, order) 
# Order list related to markers and labels. 
z1 = np.take(x1, order) 
# Order list related to sizes. 
z2 = np.take(x2, order) 
# Order list related to colors. 
z3 = np.take(x3, order) 

plt.figure() 
cm = plt.cm.get_cmap('RdYlBu') 

# Scatter plot where each value in z1 has a different marker and label 
# assigned. 
mrk = {7: ('o', '7'), 8: ('s', '8'), 9: ('D', '9')} 
for key, value in mrk.items(): 

    s1 = (z1 == key) 
    plt.scatter(x_o[s1], y_o[s1], marker=value[0], label=value[1], 
     s=z2[s1] * 100., c=z3[s1], cmap=cm, lw=0.2) 

# Plot colorbar 
plt.colorbar() 

# Plot legend. 
plt.legend(loc="lower left", markerscale=0.7, scatterpoints=1, fontsize=10) 

plt.show() 

回答

24

您可以獲取傳說手柄和改變自己的顏色做:

ax = plt.gca() 
leg = ax.get_legend() 
leg.legendHandles[0].set_color('red') 
leg.legendHandles[1].set_color('yellow') 
+1

謝謝你,這樣做的伎倆。 – Gabriel

+1

當你用'plt.plot'而不是'plt.scatter'繪製點時,你有沒有試過這樣做?不適合我。運行mpl v 2.0.0。 – saintsfan342000

+0

@ saintsfan342000我還沒有在這個特定的情況下嘗試過。我會盡快回復您 –

1

你可以用lh.get_label()檢索每個傳奇手柄的標籤,如果你想要將顏色映射到特定標籤。

對於我而言,它的工作最好創建從legendHandles的字典,並改變顏色,像這樣:

ax = plt.gca() 
leg = ax.get_legend() 
hl_dict = {handle.get_label(): handle for handle in leg.legendHandles} 
hl_dict['9'].set_color('red') 
hl_dict['8'].set_color('yellow')