Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib share x axis but don't show x axis tick labels for both, just one

I'm using python + matplotlib and I'm having two plots share an axis. If you try to set graph1.set_xticklabels([]) while sharing an axis, it has no effect because it is shared. Is there a way to share the axis AND be able to hide the x axis of one plot?

like image 343
thenickname Avatar asked Nov 17 '10 21:11

thenickname


People also ask

How do you prevent X-axis labels from overlapping each other in Matplotlib?

Matplotlib x-axis label overlap In matplotlib, we have a method setp() that is used to set the rotation and alignment attributes of tick labels to avoid overlapping. To get ticklabels, we use the plt. setp() and get.

How do I show all X labels in Matplotlib?

To show all X coordinates (or Y coordinates), we can use xticks() method (or yticks()).

How do I add a second X-axis in Matplotlib?

We can use the twiny() method to create a second X-axis. Similarly, using twinx, we can create a shared Y-axis.


1 Answers

This is a common gotcha when using shared axes.

Fortunately, there's a simple fix: use plt.setp(ax.get_xticklabels(), visible=False) to make the labels invisible on just one axis.

This is equivalent to [label.set_visible(False) for label in ax.get_xticklabels()], for whatever it's worth. setp will automatically operate on an iterable of matplotlib objects, as well as individual objects.

As an example:

import matplotlib.pyplot as plt fig = plt.figure() ax1 = fig.add_subplot(2,1,1) ax1.plot(range(10), 'b-')  ax2 = fig.add_subplot(2,1,2, sharex=ax1) ax2.plot(range(10), 'r-')  plt.setp(ax1.get_xticklabels(), visible=False)  plt.show() 

alt text

like image 153
Joe Kington Avatar answered Sep 21 '22 13:09

Joe Kington