如何修复 matplotlib .title() TypeError: 'Text' object is not callable

问题:

你想使用 .title("My title") 设置 matplotlib 图表的标题,但你看到类似这样的错误消息

matplotlib_title_trace.txt
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-f5f930f00eac> in <module>
---> 10 axs[0].title("My title")

TypeError: 'Text' object is not callable

解决方案

使用 .set_title("My title") 而不是 .title("My title")

While

matplotlib_title_set_example.py
from matplotlib import pyplot as plt

plt.title("My title")

工作正常,如果你有从 plt.subplots() 获取的 axes 对象,你必须使用 set_title()

matplotlib_title_axes_example.py
from matplotlib import pyplot as plt
fig, axs = plt.subplots(2, 1)
# ...
axs[0].set_title("My title")

Check out similar posts by category: Python