python - matplotlib 中的图例问题

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

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

最佳答案

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

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/

相关文章:

python 子进程

python - 有没有办法从一个窗口更改另一个窗口的标签?

python - 我似乎无法让我的 flask 应用程序显示我的表单-flask_wtf

python - 为 AxesImage 自定义刻度?

android - BarChart 上的 Int 值

python - 未收到 SMTPlib 附件

matplotlib - 如何控制 matplotlib 中的词干标记大小?

python - 从具有可变 x 轴的数组绘制曲线

javascript - 异步加载 Chart.js 工具提示信息

r - 绘制 R 中单列的总和