0

This code only produces one figure with two plots on it

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
def squareX(x):
    return x*x

fig,ax=plt.subplots()
i=np.arange(5)
j=squareX(i)
print(i,j)
figure0=plt.plot(i,j)
#plt.show()

#fig,ax=plt.subplots()# if you omit this then a new plot wont show-you therefore need to show the plot before
x = np.random.rand(10)
y = np.random.rand(10)
figure1 = plt.plot(x,y)

Question 1. The first call to

fig,ax=plt.subplots()

returns two variables that are never used. Rather, the two plots are made using

figure0 = plt.plot(x,y)

and

figure1 = plt.plot(x,y)

Why does matplotlib decide to output them both after the second call? What makes the first call to figure0 = plt.plot(x,y) invisible until the end?

Question 2) If first commented line is UNCOMMENTED, then matplotlib displays two figures. I can understand that plt.show() after the first call to figure0 = plt.plot(x,y) causes matplotlib to draw a figure but there is no call to plt.show() after the call to figure1 = plt.plot(x,y) but figure1 still gets drawn.

Question 3) If the second commented line is UNCOMMENTED then matplotlib displays two figures. But still, the second uncommented line seems almost irrelevant as its variables are never used.

I realize this is a VERY BASIC question and refers to the 'underworkings'of matplotlib. Please forgive me if it has been CLEARLY addressed somewhere but there seems to be a lot of disconnected documentation about matplotlib. If you have a link for a simpleton like me I would appreciate it.

aquagremlin
  • 3,515
  • 2
  • 29
  • 51
  • I think you're overwhelmed by the combination of two systems that each in itself are probably much easier to understand. System 1 is pyplot. `plt.subplots()` creates a figure. `plt.plot()` either creates a figure, if none is open already, else will use the current open figure. Whenever `show()` is called, all open figures will be displayed. System 2 is IPython, or specifically the IPykernel inline backend. It will interfere with matplotlib, such that at the end of a cell it will `show()` all pyplot figures, no matter whether you call that command yourself. – ImportanceOfBeingErnest Mar 07 '20 at 20:07
  • I did not know that two systems were operating. If I run the python interpreter by typing 'python' at the command line and then type '>>> matplotlib.get_backend()' I get 'Qt5Agg'. If I do the same in a jupyter cell (or in a colab notebook) , I get 'module://ipykernel.pylab.backend_inline'. In addition it seems python has an OO interface for plotting (using fig,ax symbology) as well as a procedural interface using plt symbology. This post also confused me. https://stackoverflow.com/questions/37970424/what-is-the-difference-between-drawing-plots-using-plot-axes-or-figure-in-matpl – aquagremlin Mar 08 '20 at 00:25

0 Answers0