10

I've create the following set of subplots using the following function:

def create31fig(size,xlabel,ylabel,title=None):
    fig = plt.figure(figsize=(size,size))
    ax1 = fig.add_subplot(311)
    ax2 = fig.add_subplot(312)
    ax3 = fig.add_subplot(313)
    plt.subplots_adjust(hspace=0.001)
    plt.subplots_adjust(wspace=0.001)
    ax1.set_xticklabels([])
    ax2.set_xticklabels([])
    xticklabels = ax1.get_xticklabels()+ ax2.get_xticklabels()
    plt.setp(xticklabels, visible=False)
    ax1.set_title(title)
    ax2.set_ylabel(ylabel)
    ax3.set_xlabel(xlabel)
    return ax1,ax2,ax3

How do I make sure the top and bottom of subplot(312) do not overlap with their neighbours? Thanks.

Subplot

Griff
  • 2,064
  • 5
  • 31
  • 47
  • 2
    Don't know if it'll necessarily work for this configuration, but have a look at [this thread](http://stackoverflow.com/questions/2418125/matplotlib-subplots-adjust-hspace-so-titles-and-xlabels-dont-overlap). Otherwise, the easiest thing to do would be to simply remove one of the overlapping tick labels: `ax1.get_yticklabels()[0].set_visible(False)` – Sajjan Singh Apr 02 '13 at 20:08

1 Answers1

18

In the ticker module there is a class called MaxNLocator that can take a prune kwarg.
Using that you can remove the topmost tick of the 2nd and 3rd subplots:

import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator # added 

def create31fig(size,xlabel,ylabel,title=None):
    fig = plt.figure(figsize=(size,size))
    ax1 = fig.add_subplot(311)
    ax2 = fig.add_subplot(312)
    ax3 = fig.add_subplot(313)
    plt.subplots_adjust(hspace=0.001)
    plt.subplots_adjust(wspace=0.001)
    ax1.set_xticklabels([])
    ax2.set_xticklabels([])
    xticklabels = ax1.get_xticklabels() + ax2.get_xticklabels()
    plt.setp(xticklabels, visible=False)
    ax1.set_title(title)
    nbins = len(ax1.get_xticklabels()) # added 
    ax2.yaxis.set_major_locator(MaxNLocator(nbins=nbins, prune='upper')) # added 
    ax2.set_ylabel(ylabel)
    ax3.yaxis.set_major_locator(MaxNLocator(nbins=nbins,prune='upper')) # added 
    ax3.set_xlabel(xlabel)
    return ax1,ax2,ax3

create31fig(5,'xlabel','ylabel',title='test')

Sample image after making those adjustments:

enter image description here

Aside: If the overlapping x- and y- labels in the lowest subplot are an issue consider "pruning" one of those as well.

mechanical_meat
  • 163,903
  • 24
  • 228
  • 223