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

使用pd.DataFrame绘制堆叠柱状图时,调用plt.legend()触发TypeError问题排查

问题:调用plt.legend()绘制堆叠柱状图图例时触发TypeError

我用pd.DataFrame绘制堆叠柱状图,图表其他功能均正常,但调用plt.legend()时始终触发TypeError,带参数调用plt.legend([])或plt.legend(loc='upper center')也会报同样的错误。

代码示例

df.plot(x='Bucket', 
             kind='bar', 
             stacked=True,
             figsize=(10, 10),
          )


plt.ylabel('Emails', fontsize=20)
plt.xlabel('Character Length of Emails', fontsize=20)
plt.title('Email Topics vs Email Length', fontsize=30)
plt.xticks(rotation = 25, fontsize=15)
plt.yticks(rotation = 25, fontsize=15)

plt.legend()

错误信息

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-554-876a190bbc34> in <module>
     22 plt.yticks(rotation = 25, fontsize=15)
     23 
---> 24 plt.legend()
     25 
     26 

TypeError: 'list' object is not callable

原因及解决方法

  • 核心原因:你之前的代码里大概率不小心把plt.legend这个函数名赋值成了列表(比如写过plt.legend = [xxx, yyy]这类语句),覆盖了matplotlib原本的legend()函数,导致现在调用时实际是在尝试调用一个列表,因此触发TypeError。
  • 解决步骤:
    1. 检查所有代码,找出并删除把plt.legend赋值为列表的语句。
    2. 如果是在Jupyter Notebook/Lab这类交互式环境中,直接重启内核后重新运行代码,清除变量污染。
    3. 也可以重新导入pyplot模块恢复函数定义:
      from matplotlib import pyplot as plt
      

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 20:36:27