2013-07-22 75 views
1

隨着matplotlib我創建乾地塊,設置軸情節顏色,並創造了情節的傳說是這樣的:matplotlib:改變乾圖例顏色

import pyplot as plt 
... 

plots, legend_names = [], [] 

for x_var in x_vars: 
    plots.append(plt.stem(plt.stem(dataframe[y_var], dataframe[x_var]))) 

    markerline, stemlines, baseline = plots[x_var_index] 
    plt.setp(stemlines, linewidth=2, color=numpy_rand(3,1))  # set stems to random colors 
    plt.setp(markerline, 'markerfacecolor', 'b')    # make points blue 

    legend_names.append(x_var) 
... 

plt.legend([plot[0] for plot in plots], legend_names, loc='best') 

結果看起來是這樣的:

enter image description here

我猜測圖例中的第一個點應該對應點顏色(如圖中所示),而第二個點應該對應於幹/線顏色。然而,莖和點的顏色最終都對應於圖中點的顏色。有沒有辦法來解決這個問題?謝謝。

回答

2

圖例的默認值是顯示兩個標記。你可以用參數numpoints = 1來改變它。您的圖例命令正在使用標記,而不是線條作爲輸入使用plot[0]。不幸的是,這些莖不是支持藝術家的圖例,所以你需要使用代理藝術家。這裏有一個例子:

import pylab as plt 
from numpy import random 

plots, legend_names = [], [] 

x1 = [10,20,30] 
y1 = [10,20,30] 
# some fake data 
x2 = [15, 25, 35] 
y2 = [15, 25, 35] 
x_vars = [x1, x2] 
y_vars = [y1, y2] 
legend_names = ['a','b'] 

# create figure 
plt.figure() 
plt.hold(True) 

plots = [] 
proxies = [] 


for x_var, y_var in zip(x_vars, y_vars): 
    markerline, stemlines, baseline = plt.stem(x_var, y_var) 
    plots.append((markerline, stemlines, baseline)) 

    c = color = random.rand(3,1) 

    plt.setp(stemlines, linewidth=2, color=c)  # set stems to random colors 
    plt.setp(markerline, 'markerfacecolor', 'b') # make points blue 

    #plot proxy artist 
    h, = plt.plot(1,1,color=c) 
    proxies.append(h) 
# hide proxies  
plt.legend(proxies, legend_names, loc='best', numpoints=1) 
for h in proxies: 
    h.set_visible(False) 
plt.show() 

enter image description here

+0

真棒。謝謝! – Lamps1829