Home > Enterprise >  How does matplotlib knows which Figure object to associate with which Axes object?
How does matplotlib knows which Figure object to associate with which Axes object?

Time:11-06

I am currently learning matplotlib using a book named "python data science handbook". I found various instances where the OOP interface of matplotlib is used rather than matlab style interface. Example:

fig = plt.figure()
ax = plt.axes()

x = np.linspace(0, 10, 1000)
ax.plot(x, np.sin(x));

I want to know, ho does the fig object get associated with the ax object, we have not used any function that binds ax object with that specific fig object . But the program is still working. If i could get an explanation or a link for the documentation, it would be a lot helpful. same types of questions has been previously asked but have not been properly answered.

CodePudding user response:

matplotlib.pyplot maintains a record of all existing figures, assigning to each figure a number (1, 2,...). It also keeps track which figure is currently active.

plt.axes() adds an axes object to the currently active figure. The first line of the source code of this function is fig = gcf() which gets this figure.

A newly created figure automatically becomes active, but you can make any existing figure active at any point using its number. For example, plt.figure(2) will make figure 2 active. You can get the numbers of all existing figures using plt.get_fignums(), and check the number of the currently active figure using plt.gcf().number.

  • Related