matplotlib:改变词干图传奇色彩

时间:2013-07-22 15:29:39

标签: python 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

我猜测图例中的第一个点应该对应于点颜色(如图中所示),而第二个点应该对应于词干/线条颜色。但是,茎和点颜色最终都对应于图中点的颜色。有没有办法来解决这个问题?感谢。

1 个答案:

答案 0 :(得分:3)

图例的默认设置是显示两个标记。您可以使用参数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