python matplotlib图例仅显示列表的第一个条目 [英] python matplotlib legend shows first entry of a list only
本文介绍了python matplotlib图例仅显示列表的第一个条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法让所有图例出现在matplotlib中.
I could not get all the legends to appear in matplotlib.
我的标签"数组是:
lab = ['Google', 'MSFT', 'APPL', 'EXXON', 'WMRT']
我使用以下代码添加图例:
I use the below code to add the legend:
ax.legend(lab,loc="best")
我只看到右上角的Google".如何显示所有标签?
Am seeing only 'Google' in top right corner. How to show all labels?
完整代码:
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的回答可能更有用 *,但不能回答问题.只需为图例创建单独的条形图,您将获得所需的结果:
The answer by @Ffisegydd may be more useful*, but it doesn't answer the question. Simply create separate bar charts for the legend, and you'll get the desired result:
for x,y,c,lb in zip(ind,menMeans,my_colors,lab):
ax.bar(x, y, width, color=c,label=lb)
ax.legend()
* 要了解为什么此演示文稿可能有害,请考虑如果观看者是色盲(或以黑白打印)会发生什么情况.
* To see why this presentation may be harmful, consider what would happen if the viewer was colorblind (or this was printed in black and white).
这篇关于python matplotlib图例仅显示列表的第一个条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文