簡體   English   中英

matplotlib中的圖例問題

[英]Issue with legend in matplotlib

因此,我有一個比較條形圖,可以正確地繪制數據,但是每當我嘗試調用圖例方法時,我總是收到錯誤消息:“沒有找到帶有放置在圖例中的標簽的手柄”

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

條形圖上的其他所有內容都正確,但是我無法顯示圖例

legend()顯示“標簽”值。 您可以在繪圖功能中或使用set_label()

嘗試:

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

這是因為在繪制條形圖時,您沒有指定任何標簽。 最簡單的方法是在繪圖時傳遞標簽。 就您而言,它看起來像

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM