Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib plt.xlabel() vs ax.set_xlabel()

I am using some code that uses the singleton-version of matplotlib in Python, i.e. it has calls like

plt.figure()
...
plt.xlabel("abc")

I am trying to convert it to the functional/memory-less version:

fig,ax = plt.subplots()
...
ax.set_xlabel("abc")

A couple questions:

  • Is there an option to set the xlabel of an axes directly? Something like ax.xlabel = "xlabel string"?

  • From the documentation, it seems like this is not possible. (not even a private attribute we can set)

  • Or is it always required to go through the setter? This has always confused me and struck me as non-Pythonic.

  • Why did the API change going from plt.xlabel() to ax.set_xlabel()?

like image 470
information_interchange Avatar asked Oct 24 '25 05:10

information_interchange


1 Answers

Matplotlib had the pyplot interface, and then later developed the object-oriented interface, as described in the documentation (https://matplotlib.org/3.2.1/tutorials/introductory/lifecycle.html).

The latter is now preferred, so use fig, ax = plt.subplots and then use the setter method on ax.

like image 103
Eric Truett Avatar answered Oct 26 '25 17:10

Eric Truett