Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove xtics from an axis in matplotlib? [duplicate]

I'm using subplots in matplotlib. Since all of my subplots have the same x-axis, I only want to label the x-axis on my bottom plot. How can I remove xtics from just one axis?

like image 616
Dan Avatar asked Mar 17 '26 03:03

Dan


2 Answers

As pointed out here, the following works!

plt.tick_params(\
    axis='x',          # changes apply to the x-axis
    which='both',      # both major and minor ticks are affected
    bottom='off',      # ticks along the bottom edge are off
    top='off',         # ticks along the top edge are off
    labelbottom='off') # labels along the bottom edge are off
like image 106
StackG Avatar answered Mar 18 '26 17:03

StackG


Dan, if you've set up your plots in an OOP way using

import matplotlib.pyplot as plt
fig, ax_arr = subplots(3, 1, sharex=True)

then it should be easy to hide the x-axis labels using something like

plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False)
# or
plt.setp([a.get_xticklabels() for a in ax_arr[:-1]], visible=False)

But check out this link and some of the further down examples will prove useful.

Edit:

If you can't use plt.subplots(), I'm still assuming you can do

import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)

ax1.plot(x1, y1)
ax2.plot(x2, y2)

plt.setp(ax1.get_xticklabels(), visible=False)

If you have more than 2 subplots, such as

ax1 = fig.add_subplot(N11)
ax2 = fig.add_subplot(N12)
...
axN = fig.add_subplot(N1N)

plt.setp([a.get_xticklabels() for a in (ax1, ..., axN-1)], visible=False)
like image 36
wflynny Avatar answered Mar 18 '26 16:03

wflynny