Tom Johnson Tom Johnson - 2 months ago 19
Python Question

How to get rid of extra white space on subplots with shared axes?

I'm creating a plot using python 3.5.1 and matplotlib 1.5.1 that has two subplots (side by side) with a shared Y axis. A sample output image is shown below:

Sample Image

Notice the extra white space at the top and bottom of each set of axes. Try as I might I can't seem to get rid of it. The overall goal of the figure is to have a waterfall type plot on the left with a shared Y axes with the plot on the right.

Here's some sample code to reproduce the image above.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
%matplotlib inline

# create some X values

periods = np.linspace(1/1440, 1, 1000)

# create some Y values (will be datetimes, not necessarily evenly spaced
# like they are in this example)

day_ints = np.linspace(1, 100, 100)
days = pd.to_timedelta(day_ints, 'D') + pd.to_datetime('2016-01-01')

# create some fake data for the number of points
points = np.random.random(len(day_ints))

# create some fake data for the color mesh

Sxx = np.random.random((len(days), len(periods)))

# Create the plots

fig = plt.figure(figsize=(8, 6))

# create first plot

ax1 = plt.subplot2grid((1,5), (0,0), colspan=4)
im = ax1.pcolormesh(periods, days, Sxx, cmap='viridis', vmin=0, vmax=1)
ax1.invert_yaxis()
ax1.autoscale(enable=True, axis='Y', tight=True)

# create second plot and use the same y axis as the first one

ax2 = plt.subplot2grid((1,5), (0,4), sharey=ax1)
ax2.scatter(points, days)
ax2.autoscale(enable=True, axis='Y', tight=True)

# Hide the Y axis scale on the second plot
plt.setp(ax2.get_yticklabels(), visible=False)
#ax1.set_adjustable('box-forced')
#ax2.set_adjustable('box-forced')

fig.colorbar(im, ax=ax1)


As you can see in the commented out code I've tried a number of approaches, as suggested by posts like https://github.com/matplotlib/matplotlib/issues/1789/ and Matplotlib: set axis tight only to x or y axis.

As soon as I remove the
sharey=ax1
part of the second subplot2grid call the problem goes away, but then I also don't have a common Y axis.

Answer

Autoscale tends to add a buffer to the data so that all of the data points are easily visible and not part-way cut off by the axes.

Change:

ax1.autoscale(enable=True, axis='Y', tight=True)

to:

ax1.set_ylim(days.min(),days.max())

and

ax2.autoscale(enable=True, axis='Y', tight=True)

to:

ax2.set_ylim(days.min(),days.max())

To get:

enter image description here

Comments