python matplotlib 图例仅显示列表的第一个条目

标签 python matplotlib

我无法让所有图例出现在 matplotlib 中。

我的标签数组是:

lab = ['Google', 'MSFT', 'APPL', 'EXXON', 'WMRT']

我使用下面的代码添加图例:

ax.legend(lab,loc="best")

我在右上角只看到“Google”。如何显示所有标签? enter image description here

完整代码:

import numpy as np
import matplotlib.pyplot as plt
from itertools import cycle, islice

menMeans = (8092, 812, 2221, 1000, 562)
N = len(menMeans)

lab = ['Google', 'MSFT', 'APPL', 'EXXON', 'WMRT']

ind = np.arange(N)  # the x locations for the groups
width = 0.35       # the width of the bars

fig, ax = plt.subplots()
my_colors = list(islice(cycle(['b', 'r', 'g', 'y', 'k']), None, N))
rects1 = ax.bar(ind, menMeans, width, color=my_colors,label=lab)

# add some
ax.set_ylabel('Count')
ax.set_title('Trending words and their counts')
ax.set_xticks(ind+width)
ax.legend(lab,loc="best")
plt.show()

最佳答案

@Ffisegydd 的回答可能更有用*,但它没有回答问题。只需为图例创建单独的条形图,您就会得到想要的结果:

for x,y,c,lb in zip(ind,menMeans,my_colors,lab):
    ax.bar(x, y, width, color=c,label=lb)

ax.legend()

enter image description here

* 要了解此演示文稿为何有害,请考虑如果观看者是色盲(或黑白打印)会发生什么情况。

关于python matplotlib 图例仅显示列表的第一个条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23317150/

相关文章:

python - 合并特定列上的两个大型数据框并显示进度条

python - 如何使用python将稀疏矩阵转换为密集形式

python - set_position() 后的 matplotlib twinx 奇怪行为

Python:在坐标系中显示随机点

python - 如何在 wagtail 中从 zip 存档制作图片库?

python - 给定 Python 中前缀表示法的字符串表达式,递归创建二叉树

python - 使用python和imaplib的gmail登录失败

python - 如何根据某些变量更改数据点颜色

Python Plotly : Percentage Axis Formatter

python - X 轴标签被图形截断 - Python Matplotlib