Moving x-axis to the top of a plot in matplotlib Moving x-axis to the top of a plot in matplotlib python python

Moving x-axis to the top of a plot in matplotlib


Use

ax.xaxis.tick_top()

to place the tick marks at the top of the image. The command

ax.set_xlabel('X LABEL')    ax.xaxis.set_label_position('top') 

affects the label, not the tick marks.

import matplotlib.pyplot as pltimport numpy as npcolumn_labels = list('ABCD')row_labels = list('WXYZ')data = np.random.rand(4, 4)fig, ax = plt.subplots()heatmap = ax.pcolor(data, cmap=plt.cm.Blues)# put the major ticks at the middle of each cellax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)# want a more natural, table-like displayax.invert_yaxis()ax.xaxis.tick_top()ax.set_xticklabels(column_labels, minor=False)ax.set_yticklabels(row_labels, minor=False)plt.show()

enter image description here


You want set_ticks_position rather than set_label_position:

ax.xaxis.set_ticks_position('top') # the rest is the same

This gives me:

enter image description here


tick_params is very useful for setting tick properties. Labels can be moved to the top with:

    ax.tick_params(labelbottom=False,labeltop=True)