How to fix matplotlib .xlabel() AttributeError: 'AxesSubplot' object has no attribute 'xlabel'
Problem:
You want to set the xlabel of a matplotlib plot using .xlabel("My xlabel") but you see an error messsage like
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'Solution
Use .set_xlabel("My xlabel") instead of .xlabel("My xlabel") !
While
matplotlib_plt_xlabel_example.py
from matplotlib import pyplot as plt
plt.xlabel("My xlabel")works fine, if you have an axes object like the one you get from plt.subplots(), you’ll have to use 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
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow