25

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?

Infinite Recursion
  • 6,511
  • 28
  • 39
  • 51
Osmond Bishop
  • 7,560
  • 14
  • 42
  • 51
  • 3
    Could you add some of your code? –  Nov 27 '12 at 03:11
  • 2
    You can specify the tick labels and positions manually for greater control: see example code in the matplotlib docs. http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.xticks – abought Nov 27 '12 at 05:27

3 Answers3

36

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.

Bruno Gelb
  • 5,322
  • 8
  • 35
  • 50
  • If you want to hide the ticks markers too and not just the labels for the ticks, use ```xticks[0].set_visible(False)``` and ```xticks[1].set_visible(False)``` – Bikash Gyawali Jan 17 '20 at 00:04
2

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([])
Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234
1

I wanted to have ticks for each number from 0 to 30, but the labels looked messy, so I showed only multiples of 5 by doing this:

pyplot.xticks(numpy.arange(0,31,1), [i if i in range(0,31,5) else '' for i in range(31)])

You could apply the same method and exclude labeling for the first and last elements of your dataset.

SherylHohman
  • 16,580
  • 17
  • 88
  • 94
Rikku
  • 13
  • 4