如何修复 matplotlib .ylabel() AttributeError: 'AxesSubplot' object has no attribute 'ylabel'

问题:

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

attribute_error.txt
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-12-28a87d95bccc> in <module>
---> 11 axs[0].ylabel("My ylabel")

AttributeError: 'AxesSubplot' object has no attribute 'ylabel'

解决方案

使用 .set_ylabel("My ylabel") 而不是 .ylabel("My ylabel")

While

plt_ylabel_example.py
from matplotlib import pyplot as plt

plt.ylabel("My ylabel")

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

plt_set_ylabel.py
from matplotlib import pyplot as plt
fig, axs = plt.subplots(2, 1)
# ...
axs[0].set_ylabel("My ylabel")

Check out similar posts by category: Python