how to show tick labels on top of matplotlib plot?

Question:

In matplotlib what is the way to have tick labels both at the bottom and in the top x axis? I have searched a lot and still can’t find how to do it.

Asked By: elyase

||

Answers:

You can do it with twiny():

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny()
X2tick_location= ax1.xaxis.get_ticklocs() #Get the tick locations in data coordinates as a numpy array
ax2.set_xticks(X2tick_location)
ax2.set_xticklabels(X2tick_location)
plt.show()

enter image description here

Have a look to this question too for more elaborate plots.

Answered By: G M

Sorry, I lied in the comments. You can do this easily (but it seems to be badly documented)

fig, ax = plt.subplots(1, 1)
ax.xaxis.set_tick_params(labeltop='on')

output

Answered By: tacaswell

This seems to be the standard way as of v3.5:

fig, ax = plt.subplots()
ax.tick_params('x', top=True, labeltop=True)

figure with ticks and labels on top

Note that the top keyword draws the ticks and the labeltop keyword draws the labels. Documentation here.

Answered By: kjohnsen
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.