Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What can I do about the overlapping labels in these subplots?

Below is a figure I created with matplotlib. The problem is pretty obvious -- the labels overlap and the whole thing is an unreadable mess.

enter image description here

I tried calling tight_layout for each subplot, but this crashes my ipython-notebook kernel.

What can I do to fix the layout? Acceptable approaches include fixing the xlabel, ylabel, and title for each subplot, but another (and perhaps better) approach would be to have a single xlabel, ylabel and title for the entire figure.

Here's the loop I used to generate the above subplots:

for i, sub in enumerate(datalist):
    subnum = i + start_with
    subplot(3, 4, i)

     # format data (sub is a PANDAS dataframe)
    xdat = sub['x'][(sub['in_trl'] == True) & (sub['x'].notnull()) & (sub['y'].notnull())]
    ydat = sub['y'][(sub['in_trl'] == True) & (sub['x'].notnull()) & (sub['y'].notnull())]

    # plot
    hist2d(xdat, ydat, bins=1000)
    plot(0, 0, 'ro')  # origin

    title('Subject {0} in-Trial Gaze'.format(subnum))
    xlabel('Horizontal Offset (degrees visual angle)')
    ylabel('Vertical Offset (degrees visual angle)')

    xlim([-.005, .005])
    ylim([-.005, .005])
    # tight_layout  # crashes ipython-notebook kernel

show()

Update:

Okay, so ImageGrid seems to be the way to go, but my figure is still looking a bit wonky:

enter image description here

Here's the code I used:

fig = figure(dpi=300)
grid = ImageGrid(fig, 111, nrows_ncols=(3, 4), axes_pad=0.1)

for gridax, (i, sub) in zip(grid, enumerate(eyelink_data)):
    subnum = i + start_with

     # format data
    xdat = sub['x'][(sub['in_trl'] == True) & (sub['x'].notnull()) & (sub['y'].notnull())]
    ydat = sub['y'][(sub['in_trl'] == True) & (sub['x'].notnull()) & (sub['y'].notnull())]

    # plot
    gridax.hist2d(xdat, ydat, bins=1000)
    plot(0, 0, 'ro')  # origin

    title('Subject {0} in-Trial Gaze'.format(subnum))
    xlabel('Horizontal Offset\n(degrees visual angle)')
    ylabel('Vertical Offset\n(degrees visual angle)')

    xlim([-.005, .005])
    ylim([-.005, .005])

show()
like image 499
Louis Thibault Avatar asked Oct 21 '22 14:10

Louis Thibault


1 Answers

You want ImageGrid (tutorial).

First example lifted directly from that link (and lightly modified):

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
import numpy as np

im = np.arange(100)
im.shape = 10, 10

fig = plt.figure(1, (4., 4.))
grid = ImageGrid(fig, 111, # similar to subplot(111)
                nrows_ncols = (2, 2), # creates 2x2 grid of axes
                axes_pad=0.1, # pad between axes in inch.
                aspect=False, # do not force aspect='equal'
                )

for i in range(4):
    grid[i].imshow(im) # The AxesGrid object work as a list of axes.

plt.show()
like image 189
tacaswell Avatar answered Oct 24 '22 06:10

tacaswell