所以我有一个比较条形图,可以正确绘制数据,但是每当我尝试调用图例方法时,我总是收到错误消息“没有找到可放入图例的标签句柄”
def plotSiteByYear(dict1, dict2):
''' creates a bar chart comparison of the cancer sites of chosen years
'''
values1 = dict1.values() # y values of dictionaries
values2 = dict2.values()
oKeys = [] # creating empty lists first
nKeys = []
oKeys = list(dict1.keys()) # x values of dictionaries
nKeys = list(dict2.keys())
x1 = list(range(len(oKeys)))
ind = np.arange(len(dict1))
width = 0.4
opacity = 0.7
fig, ax = plt.subplots()
#plotting older year (2005)
rects1 = plt.bar(ind - width/2, values1, width, alpha = opacity, color = '#2d4dff', align='center',)
#plotting more recent year (2015)
rect2 = plt.bar(ind + width/2, values2, width, alpha = opacity, color = '#d4bee8', align='center')
# labels / legend
ax.set_ylabel('Number of Cancer Incidences')
ax.set_xlabel('Location of Cancer Site')
ax.set_title('Number of Cancer Incidences by Site in 2005 vs. 2015')
ax.set_xticks(x1)
ax.set_xticklabels(oKeys, rotation=90)
# need to add a legend
ax.legend()
plt.show()
我的条形图的其他所有内容都是正确的,但我无法显示图例
最佳答案
这是因为在绘制条形图时,您没有指定任何标签。最简单的方法是在绘图时传递标签。在你的情况下,它看起来像
fig, ax = plt.subplots()
rects1 = plt.bar(ind - width/2, values1, width, alpha=opacity,
color='#2d4dff', align='center',label='2005') # <--- Label added here
rect2 = plt.bar(ind + width/2, values2, width, alpha=opacity,
color='#d4bee8', align='center', label='2015') # <--- Label added here
# Rest of the code
ax.legend()
关于python - matplotlib 中的图例问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55821629/