matplotlib Axes.plot() vs pyplot.plot()

For drawing a single plot, the best practice is probably

fig = plt.figure()
plt.plot(data)
fig.show()

Now, lets take a look in to 3 examples from the question and explain what they do.

  1. Takes the current figure and axes (if none exists it will create a new one) and plot into them.

    line = plt.plot(data)
    
  2. In your case, the behavior is same as before with explicitly stating the
    axes for plot.

     ax = plt.axes()
     line = ax.plot(data)
    

This approach of using ax.plot(...) is a must, if you want to plot into multiple axes (possibly in one figure). For example when using a subplots.

  1. Explicitly creates new figure – you will not add anything to previous one.
    Explicitly creates a new axes with given rectangle shape and the rest is the
    same as with 2.

     fig = plt.figure()
     ax = fig.add_axes([0,0,1,1])
     line = ax.plot(data)
    

possible problem using figure.add_axes is that it may add a new axes object
to the figure, which will overlay the first one (or others). This happens if
the requested size does not match the existing ones.

Leave a Comment