Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing xticks from overlapping yticks

How can I prevent the labels of xticks from overlapping with the labels of yticks when using hist (or other plotting commands) in matplotlib?

                                                          enter image description here

like image 665
Amelio Vazquez-Reina Avatar asked Oct 05 '22 22:10

Amelio Vazquez-Reina


2 Answers

There are several ways.

One is to use the tight_layout method of the figure you are drawing, which will automatically try to optimize the appareance of the labels.

fig, ax = subplots(1)
ax.plot(arange(10),rand(10))
fig.tight_layout()

An other way is to modify the rcParams values for the ticks formatting:

 rcParams['xtick.major.pad'] = 6

This will draw the ticks a little farter from the axes. after modifying the rcparams (this of any other, you can find the complete list on your matplotlibrc configuration file), remember to set it back to deafult with the rcdefaults function.

A third way is to tamper with the axes locator_params telling it to not draw the label in the corner:

fig, ax = subplots(1)
ax.plot(arange(10),rand(10))
ax.locator_params(prune='lower',axis='both')

the axis keywords tell the locator on which axis it should work and the prune keyword tell it to remove the lowest value of the tick

like image 135
EnricoGiampieri Avatar answered Oct 10 '22 03:10

EnricoGiampieri


Try increasing the padding between the ticks on the labels

import matplotlib
matplotlib.rcParams['xtick.major.pad'] = 8 # defaults are 4
matplotlib.rcParams['ytick.major.pad'] = 8 

same goes for [x|y]tick.minor.pad.

Also, try setting: [x|y]tick.direction to 'out'. That gives you a little more room and helps makes the ticks a little more visible -- especially on histograms with dark bars.

like image 26
Paul H Avatar answered Oct 10 '22 04:10

Paul H