Arturo Sbr
Arturo Sbr

Reputation: 6323

Move ticks and labels to the top of a pyplot figure

As per this question, moving the xticks and labels of an AxesSubplot object can be done with ax.xaxis.tick_top(). However, I cannot get this to work with multiple axes inside a figure.

Essentially, I want to move the xticks to the very top of the figure (only displayed at the top for the subplots in the first row).

Here's a silly example of what I'm trying to do:

fig, axs = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True)
fig.set_figheight(5)
fig.set_figwidth(10)
for ax in axs.flatten():
    ax.xaxis.tick_top()
plt.show()

Which shows

Close try

My desired result is this same figure but with the xticks and xticklabels at the top of the two plots in the first row.

Upvotes: 1

Views: 542

Answers (1)

edouard
edouard

Reputation: 121

Credits to @BigBen for the sharex comment. It is indeed what's preventing tick_top to work.

To get your results, you can combine using tick_top for the two top plots and use tick_params for the bottom two:

fig, axs = plt.subplots(2, 2, sharex=False) # Do not share xaxis
for ax in axs.flatten()[0:2]:
  ax.xaxis.tick_top()
for ax in axs.flatten()[2:]:
  ax.tick_params(axis='x',which='both',labelbottom=False) 

See a live implementation here.

Upvotes: 1

Related Questions