Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib - hiding specific ticks on x-axis

Tags:

I am trying to hide the first and last x-axis tick text of my bar plot, which is '2004' and '2013'. Matplotlib automatically adds these in by default, even though my dataset is for 2005 to 2012, hence I'd prefer not to have 2004 and 2013 in my bar plot. I'm looking for some lines of code to select and hide these ticks. Any ideas?

like image 877
Osmond Bishop Avatar asked Nov 27 '12 03:11

Osmond Bishop


People also ask

How do I remove X-axis values in Python?

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

How do I turn on minor ticks in MatPlotLib?

MatPlotLib with Python Plot x and y data points using plot() method. To locate minor ticks, use set_minor_locator() method. To show the minor ticks, use grid(which='minor').

How do I get rid of Xtick?

Use clean, fine-tipped tweezers to grasp the tick as close to the skin's surface as possible. Pull upward with steady, even pressure. Don't twist or jerk the tick; this can cause the mouth-parts to break off and remain in the skin. If this happens, remove the mouth-parts with tweezers.


2 Answers

Please, tell me if it's not what you want.

import sys, os import matplotlib.pyplot as plt  path = sys.path[0] sizes = [(12,3,), (4,3,)] x =  range(20)   for i, size in enumerate(sizes):     fig = plt.figure(figsize = size, dpi = 80, facecolor='white',edgecolor=None,linewidth=0.0, frameon=True, subplotpars=None)     ax = fig.add_subplot(111)     ax.plot(x)     plt.ylabel ('Some label')     plt.tight_layout()      make_invisible = True     if (make_invisible):         xticks = ax.xaxis.get_major_ticks()         xticks[0].label1.set_visible(False)         xticks[-1].label1.set_visible(False)  plt.show() 

This example makes invisible first and last X-ticks. But you can easily add checking for your special ticks.

like image 88
Bruno Gelb Avatar answered Oct 12 '22 03:10

Bruno Gelb


Just adding to @DmitryNazarov's answer, in case you want just to hide the tick labels, keeping the grid lines visible, use:

ax = plt.gca()      ax.axes.xaxis.set_ticklabels([]) ax.axes.yaxis.set_ticklabels([]) 
like image 36
Saullo G. P. Castro Avatar answered Oct 12 '22 03:10

Saullo G. P. Castro