Search code examples
pythonmatplotlibaxesaxis-labels

How to prevent Matplotlib from clipping away my axis labels?


I'm preparing some plots for a scientific paper, which need to be wide and short in order to fit into the page limit. However, when I save them as pdf, the x axis labels are missing, because (I think) they're outside the bounding box.

Putting the following into an iPython notebook reproduces the problem.

%pylab inline
pylab.rcParams['figure.figsize'] = (8.0, 2.0)
plot([1,5,2,4,6,2,1])
xlabel("$x$")
ylabel("$y$")
savefig("test.pdf")

The resulting pdf file looks like this: enter image description here

How can I change the bounding box of the pdf file? Ideally I'd like a solution that "does it properly", i.e. automatically adjusts the size so that everything fits neatly, including getting rid of that unnecessary space to the left and right - but I'm in a hurry, so I'll settle for any way to change the bounding box, and I'll guess numbers until it looks right if I have to.


Solution

  • You can use plt.tight_layout() to have matplotlib adjust the layout of your plot. tight_layout() will automatically adjust the dimensions, and can also be used when you have (for example) overlapping labels/ticks/etc.

    %pylab inline
    
    pylab.rcParams['figure.figsize'] = (8.0, 2.0)
    
    plot([1,5,2,4,6,2,1])
    
    xlabel("$x$")
    ylabel("$y$")
    
    tight_layout()
    
    savefig("test.pdf")
    

    Here is a .png of the output (can't upload pdfs to SO but I've checked it and it works the same way for a pdf).

    Example plot