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:
JavaScript
x
7
1
fig, axs = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True)
2
fig.set_figheight(5)
3
fig.set_figwidth(10)
4
for ax in axs.flatten():
5
ax.xaxis.tick_top()
6
plt.show()
7
Which shows
My desired result is this same figure but with the xticks
and xticklabels
at the top of the two plots in the first row.
Advertisement
Answer
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:
JavaScript
1
6
1
fig, axs = plt.subplots(2, 2, sharex=False) # Do not share xaxis
2
for ax in axs.flatten()[0:2]:
3
ax.xaxis.tick_top()
4
for ax in axs.flatten()[2:]:
5
ax.tick_params(axis='x',which='both',labelbottom=False)
6
See a live implementation here.