Nudge Subplots

In generating subplots of size 2 by 2 for this book, I've noticed that the text for the x-axis of the top subplots clashes with the titles of the lower subplots. To overcome this, I've defined nudge_subplot(), a function designed to modify the location of subplots within a figure (see Listing A-1).

Listing A-1. Source Listing of nudge_subplot()

def nudge_subplot(subp, dy):

A helper function to move subplots

sp_ax = subp.get_position() sp.set_position([sp_ax.x0, sp_ax.y0+dy, sp_ax.x1-sp_ax.x0, sp_ax.y1-sp_ax.y0])

To use the function, store the return value from subplot() and then "nudge" it by calling nudge_subplot(sp, dy), as shown in Listing A-2, where sp is the subplot and dy is the amount to nudge (a value of 0.02 for dy usually works well).

Listing A-2. Using nudge_subplot() from pylab import *

plot_cmds = [ "plot(y)", "plot(-y)", "plot(y**2)",


for i, plot_cmd in enumerate(plot_cmds): sp = subplot(2, 2, i+1) if i == 1: nudge_subplot(sp, 0.02) if i == 3: nudge_subplot(sp, -0.02) exec plot_cmd title(plot_cmd, fontsize='large') xlabel('x values')

In this code, I've nudged the right subplots and left the left ones as is, as you can see in

Figure A-1.

Overlapping -i.o Text \-L5

Overlap Fixed

Overlapping -i.o Text \-L5

Subplot Python
Figure A-1. The left subplots are unmoved (the default), and the right subplots are nudged.

The function nudge_subplot() is not backward compatible with older versions of matplot-lib. For example, with matplotlib version 0.91.4, the function set_position() accepts different arguments, and so the code needs revising. Nevertheless, the ideas are similar. Listing A-3 is an implementation that runs on matplotlib version 0.91.4.

Listing A-3. Source Listing of nudge_subplot_old(), for Older Versions of Matplotlib def nudge_subplot_old(subp, dy):

A helper function to move subplots.

Works on matplotlib version 0.91.4

sp_ax = subp.get_position() sp_ax[1] += dy sp.set_position(sp_ax)

Was this article helpful?

0 0

Post a comment