Changing x-axis tick labels when working with subplots

HHains picture HHains · Nov 5, 2013 · Viewed 22.6k times · Source

I am plotting multiple boxplots on a single figure using matplotlib following the example here:
http://matplotlib.org/examples/pylab_examples/subplots_demo.html

Everything is working as expected, but I can't figure out how to change the tick labels on the x-axis. I have four data series, which are plotting, but the x-axis ticks are labelled '1, 2, 3, 4' where I would like to assign text to these values.

My code for the plotting looks like this:

f, axarr = plt.subplots(2, sharex=True)
axarr[0].boxplot(WS_Bias, whis = 100)
#axarr[0].xticks(range(1, len(Labels)+1),Labels)
axarr[0].axhspan(-0.5, 0.5, facecolor='c', alpha = 0.2)

axarr[1].boxplot(WS_RMS, whis = 100)
#axarr[1].xticks(range(1, len(Labels)+1),Labels)
axarr[1].axhspan(0, 2, facecolor='c', alpha = 0.2)

pl.show()

The commented out lines worked to change the labels when I was dealing with only one dataset but this command is not recognized with the methods I'm using. Pyplot is imported as plt.

Answer

Francesco Montesano picture Francesco Montesano · Nov 5, 2013

Let's assume that axarr[0] has 4 visible x tick labels ([1,2,3,4]) and that you want to have instead ['a', 'b', 'c', 'd']

You can set x tick labels with the Axes method set_xticklabels just doing this:

axarr[0].set_xticklabels(['a', 'b', 'c', 'd'])

Regarding

The commented out lines worked to change the labels when I was dealing with only one dataset but this command is not recognized with the methods I'm using

xticks is not an Axes method but a function in matplotlib.pyplot, that (I think) wraps set/get_xticks and set/get_xtickslabels. So if you try to use it as in your code, you should get an error.