Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleanest way to hide every nth tick label in matplotlib colorbar?

The labels on my horizontal colorbar are too close together and I don't want to reduce text size further:

cbar = plt.colorbar(shrink=0.8, orientation='horizontal', extend='both', pad=0.02) cbar.ax.tick_params(labelsize=8) 

horizontal colorbar with bad labels

I'd like to preserve all ticks, but remove every other label.

Most examples I've found pass a user-specified list of strings to cbar.set_ticklabels(). I'm looking for a general solution.

I played around with variations of

cbar.set_ticklabels(cbar.get_ticklabels()[::2]) 

and

cbar.ax.xaxis.set_major_locator(matplotlib.ticker.MaxNLocator(nbins=4)) 

but I haven't found the magic combination.

I know there must be a clean way to do this using a locator object.

like image 200
David Shean Avatar asked Dec 02 '13 20:12

David Shean


People also ask

How do I get rid of Xlabel and Ylabel in Matplotlib?

To hide or remove X-axis labels, use set(xlabel=None). To display the figure, use show() method.

How do I show all tick labels in Matplotlib?

MatPlotLib with Python To display all label values, we can use set_xticklabels() and set_yticklabels() methods.


1 Answers

For loop the ticklabels, and call set_visible():

for label in cbar.ax.xaxis.get_ticklabels()[::2]:     label.set_visible(False) 
like image 60
HYRY Avatar answered Oct 05 '22 23:10

HYRY