matplotlib中的图例问题

时间:2019-04-24 02:40:14

标签: python matplotlib bar-chart

因此,我有一个比较条形图,可以正确地绘制数据,但是每当我尝试调用图例方法时,我都会不断收到错误消息:“没有找到带有放置在图例中的标签的手柄”

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()

条形图的其他所有内容都正确,但我无法显示图例

2 个答案:

答案 0 :(得分:0)

legend()显示“标签”值。您可以在绘图功能或set_label()

中进行设置

尝试:

rects1.set_label("MyLabel")
ax.legend()

答案 1 :(得分:0)

这是因为在绘制条形图时,您没有指定任何标签。最简单的方法是在绘图时传递标签。就您而言,它看起来像是

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()