Adding subplots with plt.figure.add_subplot()

There is an add_subplot() function similar to plt.subplot() under plt.figure() that allows us to create additional subplots under the same figure. Similar to plt.subplot(), it takes the row number, column number, and plot number as input arguments and allows arguments without commas for fewer than 10 plots.

We can also initiate the first subplot using this function. This code is a quick example:

import matplotlib.pyplot as plt

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

plt.show()

This creates an empty plot area enclosed by four spines containing the x axis and y axis, as shown below. Note that we must call the add_subplot() function under a figure but not by plt:

Let us further compare the differences between fig.add_subplot(). and  plt.subplot(). Here, we would be creating three empty subplots with different sizes and face colors.

We will first use try using fig.add_subplot():

import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111,facecolor='red')
ax2 = fig.add_subplot(121,facecolor='green')
ax3 = fig.add_subplot(233,facecolor='blue')

plt.show()

We get three overlapping subplots on the same figure, as shown below:

Next, we replace fig.add_subplot() with plt.subplot():

import matplotlib.pyplot as plt

fig = plt.figure() # Note this line is optional here
ax1 = plt.subplot(111,facecolor='red')
ax2 = plt.subplot(121,facecolor='green')
ax3 = plt.subplot(233,facecolor='blue')

plt.show()

Notice in the following image that the red ax1 subplot cannot be displayed:

If we have already plotted the first subplot using plt.subplot() and would like to create additional subplots, we can call the plt.gcf() function to retrieve the figure object and store it as a variable. Then, we can call fig.add_subplot() as shown in the example before.

Hence, the following code is an alternative way to generate the three overlapping subplots:

import matplotlib.pyplot as plt

ax1 = plt.subplot(111,facecolor='red')
fig = plt.gcf() # get current figure
ax2 = fig.add_subplot(121,facecolor='green')
ax3 = fig.add_subplot(233,facecolor='blue')

plt.show()
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.168.10