python matplotlib 图例只显示列表的第一个条目
我无法让所有的图例在matplotlib中显示出来。
我的标签数组是:
lab = ['Google', 'MSFT', 'APPL', 'EXXON', 'WMRT']
我使用下面的代码来添加图例:
ax.legend(lab,loc="best")
我只在右上角看到了“Google”。怎么才能显示所有的标签呢?

完整代码:
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()
2 个回答
3
你的问题在于,你只用了一次 ax.bar
来绘制图表,因此你的图例里只能有一个项目(就是那一个图)。要解决这个问题,你可以像下面这样修改你的绘图脚本,改变 x 轴的刻度和刻度标签。
当你创建图例时,会为你通过绘图创建的每一个 matplotlib.artist
对象生成一个条目。这些对象可以是一些数据点、一条线,或者是柱状图中的一组柱子。无论你的柱状图里有 5 根还是 10 根柱子,你仍然只绘制了一个柱状图。这就意味着你的图例里最终只会有一个条目。
我使用了 ax.set_xticks(ind+width/2)
来将刻度位置放在柱子正下方,然后用你的 lab
列表设置这些标签,使用 ax.set_xticklabels(lab)
。
import numpy as np
import matplotlib.pyplot as plt
from itertools import cycle, islice
import matplotlib.ticker as mtick
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)
ax.set_ylabel('Count')
ax.set_title('Trending words and their counts')
plt.xticks(rotation=90)
ax.set_xticks(ind+width/2)
ax.set_xticklabels(lab)
plt.show()
4
@Ffisegydd 的回答可能更 有用,但并没有直接回答问题。只需为图例单独创建柱状图,这样就能得到想要的效果:
for x,y,c,lb in zip(ind,menMeans,my_colors,lab):
ax.bar(x, y, width, color=c,label=lb)
ax.legend()
* 要理解为什么这种展示方式可能有问题,可以想象一下如果观众是色盲(或者这张图是黑白打印的)会发生什么。