将x轴移动到matplotlib中的图的顶部

基于这个关于matplotlib中heatmaps的问题 ,我想把x轴标题移到plot的顶部。

import matplotlib.pyplot as plt import numpy as np column_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 cell ax.set_xticks(np.arange(data.shape[0])+0.5, minor=False) ax.set_yticks(np.arange(data.shape[1])+0.5, minor=False) # want a more natural, table-like display ax.invert_yaxis() ax.xaxis.set_label_position('top') # <-- This doesn't work! ax.set_xticklabels(row_labels, minor=False) ax.set_yticklabels(column_labels, minor=False) plt.show() 

但是,调用matplotlib的set_label_position (如上所述)似乎没有预期的效果。 这是我的输出:

在这里输入图像说明

我究竟做错了什么?

使用

 ax.xaxis.tick_top() 

将刻度线放在图像的顶部。 命令

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

影响标签,而不是刻度线。

 import matplotlib.pyplot as plt import numpy as np column_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 cell ax.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 display ax.invert_yaxis() ax.xaxis.tick_top() ax.set_xticklabels(column_labels, minor=False) ax.set_yticklabels(row_labels, minor=False) plt.show() 

在这里输入图像说明

你想set_ticks_position而不是set_label_position

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

这给了我:

在这里输入图像说明

tick_params对设置tick属性非常有用。 标签可以移动到顶部:

  ax.tick_params(labelbottom='off',labeltop='on') 

如果你想要蜱(不是标签)出现在顶部和底部(而不是顶部),你必须做一些额外的按摩。 我能做到这一点的唯一方法是对unutbu的代码做一些小改动:

 import matplotlib.pyplot as plt import numpy as np column_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 cell ax.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 display ax.invert_yaxis() ax.xaxis.tick_top() ax.xaxis.set_ticks_position('both') # THIS IS THE ONLY CHANGE ax.set_xticklabels(column_labels, minor=False) ax.set_yticklabels(row_labels, minor=False) plt.show() 

输出:

在这里输入图像说明

Interesting Posts