Matplotlib Axes.Plot() VS Pyplot.Plot()

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.

What is the difference between drawing plots using plot, axes or figure in matplotlib?

Method 1

plt.plot(x, y)

This lets you plot just one figure with (x,y) coordinates. If you just want to get one graphic, you can use this way.

Method 2

ax = plt.subplot()
ax.plot(x, y)

This lets you plot one or several figure(s) in the same window. As you write it, you will plot just one figure, but you can make something like this:

fig1, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)

You will plot 4 figures which are named ax1, ax2, ax3 and ax4 each one but on the same window. This window will be just divided in 4 parts with my example.

Method 3

fig = plt.figure()
new_plot = fig.add_subplot(111)
new_plot.plot(x, y)

I didn't use it, but you can find documentation.

Example:

import numpy as np
import matplotlib.pyplot as plt

# Method 1 #

x = np.random.rand(10)
y = np.random.rand(10)

figure1 = plt.plot(x,y)

# Method 2 #

x1 = np.random.rand(10)
x2 = np.random.rand(10)
x3 = np.random.rand(10)
x4 = np.random.rand(10)
y1 = np.random.rand(10)
y2 = np.random.rand(10)
y3 = np.random.rand(10)
y4 = np.random.rand(10)

figure2, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
ax1.plot(x1,y1)
ax2.plot(x2,y2)
ax3.plot(x3,y3)
ax4.plot(x4,y4)

plt.show()

Sample Image
Sample Image

Other example:

Sample Image

Understanding matplotlib: plt, figure, ax(arr)?

pyplot is the 'scripting' level API in matplotlib (its highest level API to do a lot with matplotlib). It allows you to use matplotlib using a procedural interface in a similar way as you can do it with Matlab. pyplot has a notion of 'current figure' and 'current axes' that all the functions delegate to (@tacaswell dixit). So, when you use the functions available on the module pyplot you are plotting to the 'current figure' and 'current axes'.

If you want 'fine-grain' control of where/what your are plotting then you should use an object oriented API using instances of Figure and Axes.

Functions available in pyplot have an equivalent method in the Axes.

From the repo anatomy of matplotlib:

  • The Figure is the top-level container in this hierarchy. It is the overall window/page that everything is drawn on. You can have multiple independent figures and Figures can contain multiple Axes.

But...

  • Most plotting occurs on an Axes. The axes is effectively the area that we plot data on and any ticks/labels/etc associated with it. Usually we'll set up an Axes with a call to subplot (which places Axes on a regular grid), so in most cases, Axes and Subplot are synonymous.

  • Each Axes has an XAxis and a YAxis. These contain the ticks, tick locations, labels, etc.

If you want to know the anatomy of a plot you can visit this link.

Why do many examples use `fig, ax = plt.subplots()` in Matplotlib/pyplot/python

plt.subplots() is a function that returns a tuple containing a figure and axes object(s). Thus when using fig, ax = plt.subplots() you unpack this tuple into the variables fig and ax. Having fig is useful if you want to change figure-level attributes or save the figure as an image file later (e.g. with fig.savefig('yourfilename.png')). You certainly don't have to use the returned figure object but many people do use it later so it's common to see. Also, all axes objects (the objects that have plotting methods), have a parent figure object anyway, thus:

fig, ax = plt.subplots()

is more concise than this:

fig = plt.figure()
ax = fig.add_subplot(111)

Difference between axes and axis in matplotlib?

Axis is the axis of the plot, the thing that gets ticks and tick labels. The axes is the area your plot appears in.

basic questions about fig and axes in matplotlib

It is possible to plot without setting any variables. Example:

plt.figure()
plt.plot([1, 2], [5, 8])
plt.show()

You must initialize your figure somewhere, hence plt.figure(). As you pointed out, you can also use plt.subplots():

fig, ax = plt.subplots()
ax.plot([1, 2], [5, 8])
plt.show()

Note that we did not set the ncols and nrows keyword arguments. As the default value for both is 1, we get a single axis (which is why I chose the variable name ax). For n × 1 or 1 × n subplots, the second variable returned by plt.subplots() is a one-dimensional array.

fig, axes = plt.subplots(ncols=1, nrows=2)
axes[0].plot([1, 2], [5, 8])
axes[1].plot([2, 3], [9, 3])

In the case of m × n subplots (m, n > 1), axes is a two-dimensional array.

fig, axes = plt.subplots(ncols=2, nrows=2)
axes[0][0].plot([1, 2], [5, 8])
axes[1][0].plot([2, 3], [9, 3])
axes[0][1].plot([3, 4], [5, 8])
axes[1][1].plot([4, 5], [9, 3])

Whether you use ax or axes as the name for the second variable is your own choice, but axes suggests that there are multiple axes and ax that there is only one. Of course, there are also other ways to construct subplots, as shown in your linked post.

Matplotlib: Adding an axes using the same arguments as a previous axes

This is a good example that shows the benefit of using matplotlib's object oriented API.

import numpy as np
import matplotlib.pyplot as plt

# Generate random data
data = np.random.rand(100)

# Plot in different subplots
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.plot(data)

ax2.plot(data)

ax1.plot(data+1)

plt.show()

Note: it is more pythonic to have variable names start with a lower case letter e.g. data = ... rather than Data = ... see PEP8

Top and right axes labels in matplotlib pyplot

As @Mr. T pointed out, there is no plt.secondary_xaxis method so you need the axes object

import matplotlib.pyplot as plt

plt.figure(figsize=(6, 6), constrained_layout=True, dpi=70)
x = [-0.34,-0.155,0.845,0.66,-0.34]
y = [0.76,0.24,-0.265,0.735,0.76,]

plt.plot(x, y)
plt.xlim(-1,1)
plt.ylim(-1,1)
plt.xlabel("Intraverted")
plt.ylabel("Feeling")
secax = plt.gca().secondary_xaxis('top')
secax.set_xlabel('Extraverted')
secay = plt.gca().secondary_yaxis('right')
secay.set_ylabel('Thinking')
#plt.show()
plt.savefig("out.png")

Sample Image

Better, would be just to create the axes object from the start:

fig, ax = plt.subplots(figsize=(w, h), constrained_layout=True, dpi=d)
...
ax.plot(x, y)
ax.set_xlim(-1, 1)
...
secax = ax.secondary_xaxis('top')
...
fig.savefig("out.png")

Further note the use of constrained_layout=True to make the secondary yaxis label fit on the figure.



Related Topics



Leave a reply



Submit