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

问题:

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

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

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

解决方案

使用 .set_xlabel("My xlabel") 而不是 .xlabel("My xlabel")

While

matplotlib_plt_xlabel_example.py
from matplotlib import pyplot as plt

plt.xlabel("My xlabel")

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

matplotlib_axes_set_xlabel_example.py
from matplotlib import pyplot as plt
fig, axs = plt.subplots(2, 1)
# ...
axs[0].set_xlabel("My xlabel")

Check out similar posts by category: Python