You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib中条形图与折线图获取Label的差异原因

问题

现有如下DataFrame:

date         Ta
0   2018-01-01  -22.8
1   2018-01-02  -14.2
2   2018-01-03  -10.7
3   2018-01-04  -13.5
4   2018-01-05  -10.6
5   2018-01-06  -10.2
6   2018-01-07  -2.3
7   2018-01-08  0.5
8   2018-01-09  3.1
9   2018-01-10  4.7

将数据绘制成条形图时,返回类型为matplotlib.container.BarContainer,可通过get_label()获取图例标签;但绘制成折线图时,返回类型为list,调用get_label()会触发AttributeError,具体代码及报错如下:

type(ax2.bar(ex['date'],ex['Ta'],color='purple',label='Ta'))
>>> matplotlib.container.BarContainer

ax2.bar(ex['date'],ex['Ta'],color='purple',label='Ta').get_label()
>>>'Ta'
type(ax2.plot(ex['date'],ex['Ta'],color='purple',label='Ta'))
>>> list

ax2.plot(ex['date'],ex['Ta'],color='purple',label='Ta').get_label()
>>> ---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-51-c9c7cacb12b8> in <module>
----> 1 ax2.plot(ex['date'],ex['Ta'],color='purple',label='Ta').get_label()

AttributeError: 'list' object has no attribute 'get_label'

请问出现这种差异的原因是什么?

原因解析

这是Matplotlib两种绘图方法的设计逻辑差异导致的:

  1. bar()方法的返回逻辑
    bar()绘制的是一组同类型的条形元素,Matplotlib会把这些条形统一封装在BarContainer容器对象中,这个容器会直接继承你设置的label参数,所以可以直接调用容器的get_label()方法获取标签。

  2. plot()方法的返回逻辑
    plot()的设计更偏向灵活的批量绘制场景——它支持一次性传入多组数据绘制多条折线,每条折线对应一个Line2D对象。为了保持API的一致性,哪怕你只绘制一条折线,它也会把这条Line2D对象放进列表返回。

如果要获取折线的标签,需要先从列表中取出对应的Line2D对象再调用get_label(),示例代码如下:

ax2.plot(ex['date'], ex['Ta'], color='purple', label='Ta')[0].get_label()

简单来说,bar()用容器管理一组元素,plot()用列表返回多个独立的线条元素,这就是两者返回类型和调用方式不同的核心原因。

内容的提问来源于stack exchange,提问作者user88484

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 19:45:56