python - matplotlib:更改茎图图例颜色

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

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

最佳答案

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

关于python - matplotlib:更改茎图图例颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17791569/

相关文章:

python - 根据组绘制条形图

python - findAll-beautifulsoup-python 无法正常工作

python - matplotlib.animation 错误 - 系统找不到指定的文件

python - Django 积云 : syncstatic command not found

python - DJANGO:如何 list_display 反向外键属性?

python - 如何减小绘图的大小,保持数字轴相同?

python - 如何在 x 轴上设置日期刻度标签,仅适用于 matplotlib 上的给定点

python - 使用 pandas 的绘图方法在 1 行中绘制图表时出现问题

python - 在Python中,如何进行像: partial(adder , 2)(4)这样的部分函数调用?

matplotlib - 使用深色 iPython Notebook 配置文件显示 Seaborn/Matplotlib 绘图的最佳方式