Saturday, January 11, 2020

An alternative syntax for a grid of plots

By creating and specifying names for the different figure windows and subplots within them, you access the different plot windows more efficiently. For example, the following code makes four identical subplots in a single figure window using a for loop:

In [1]: fig = figure()
In [2]: ax1 = fig.add_subplot(221)
In [3]: ax2 = fig.add_subplot(222)
In [4]: ax3 = fig.add_subplot(223)
In [5]: ax4 = fig.add_subplot(224)
In [6]: for ax in [ax1, ax2, ax3, ax4]:
...: ax.plot([3,5,8],[6,3,1])
In [7]: fig.show()

The syntax introduced above for defining a Figure window and opening a grid of several subplots can be a bit cumbersome, so an alternative more compact syntax has been developed. We illustrate its use with the program below:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-2 * np.pi, 2 * np.pi, 200)
sin, cos, tan = np.sin(x), np.cos(x), np.tan(x)
csc, sec, cot = 1.0 / sin, 1.0 / cos, 1.0 / tan

plt.close('all')  # Closes all open figure windows
fig, ax = plt.subplots(2, 3, figsize=(9.5, 6),
                       sharex=True, sharey=True)
ax[0, 0].plot(x, sin, color='red')
ax[0, 1].plot(x, cos, color='orange')
ax[0, 2].plot(x, np.ma.masked_where(np.abs(tan) > 20., tan),
              color='yellow')
ax[1, 0].plot(x, np.ma.masked_where(np.abs(csc) > 20., csc),
              color='green')
ax[1, 1].plot(x, np.ma.masked_where(np.abs(sec) > 20., sec),
              color='blue')
ax[1, 2].plot(x, np.ma.masked_where(np.abs(cot) > 20., cot),
              color='violet')
ax[0, 0].set_ylim(-5, 5)
ax[0, 0].set_xlim(-2 * np.pi, 2 * np.pi)
ax[0, 0].set_xticks(np.pi * np.array([-2, -1, 0, 1, 2]))
ax[0, 0].set_xticklabels([r'-2$\pi$', r'-$\pi$', '0',
                          r'$\pi$', r'2$\pi$'])

ax[0, 2].patch.set_facecolor('lightgray')

ylab = [['sin', 'cos', 'tan'], ['csc', 'sec', 'cot']]
for i in range(2):
    for j in range(3):
        ax[i, j].axhline(color='gray', zorder=-1)
        ax[i, j].set_ylabel(ylab[i][j])

fig.savefig('figures/multiplePlotsGrid.pdf')
plt.show()


The output is shown below:


This program generates a 2-row 3-column grid of plots, as shown in the above shown figure, using the function subplots. The first two arguments of subplots specify, respectively, the number of rows and columns in the plot grid. The other arguments are optional; we will return to them after discussing the output of the function subplots.


The output of subplots is a two-element list, which we name fig and ax. The first element fig is the name given to the figure object that contains all of the subplots. The second element ax is the name
given to a 2 3 list of axes objects, one entry for each subplot. These subplots are indexed as you might expect: ax[0, 0], ax[0, 1], ax[0,2], . . .

Returning to the arguments of subplots, the first keyword argument figsize sets the overall size of the figure window. The next keyword argument, sharex=True, instructs matplotlib to create identical x axes for all six subplots; sharey=True does the same for the y axes.

Thus, in lines 21 and 22, when the limits are set for the x and y axes only for the first subplot, [0, 0], these instructions are applied to all six subplots because the keyword arguments instruct matplotlib to
make all the x axes the same and all the y axes the same. This also applies even to the tick placement and labels, which are set in lines 23–25.

You may have also noticed in lines 24 and 25 that matplotlib can print Greek letters, in this case the letter . Indeed, matplotlib can output the Greek alphabet as well as virtually any kind of mathematical
equations you can imagine using the LATEX typesetting system. The LATEX string is enclosed by $ symbols, which are inside of quotes (double or single) because it’s a string. By contrast, the subplot background is set to 'lightgray' only in plot [0, 2] in line 27.

The nested for loops in lines 30–33 place a gray line at y = 0 and labels the y-axis in each subplot. In line 37 we have added the function call fig.canvas.manager.window.raise_() in order to make the figure display in front of all the other windows on the computer. This is not necessary on all systems; on some the figure window always displays in front. If that’s not the case on your installation, you may wish to add this line.

Finally, we note that writing fig, ax = plt.subplots() without any arguments in the subplots function opens a figure window with a single subplot. It is equivalent to fig = plt.figure()
ax = fig.add_subplot(111). It’s a handy way to save a line of code.
Share:

0 comments:

Post a Comment