header_pic
Back to blog home

Matplotlib Solution for Overlapping Tick Labels Prune Keyword Argument

by Adam on 2020-05-25

Do you ever have tick labels which overlap each other? If so, you'll want to read on. The code in this post was originally written here: https://stackoverflow.com/a/15773404/42346

In the ticker module there is MaxNLocator which takes a "prune" keyword argument.

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')

Result:

And if we additionally want the lower left corner cleaned up we can also prune that, too. I leave that as an exercise for the reader.

tags: python matplotlib

Post thanked 1 time(s).

Related posts: