2013-07-22 72 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