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

基于 关于 matplotlib 中热图的问题,我想把 x 轴标题移动到情节的顶部。

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(如上所述)似乎并没有达到预期的效果:

enter image description here

我做错了什么?

151771 次浏览

你想要 set_ticks_position而不是 set_label_position:

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

这给了我:

enter image description here

使用

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()

enter image description here

你必须做一些额外的按摩,如果你想要的蜱(而不是标签)显示在顶部和底部(而不只是顶部)。我能做到这一点的唯一方法是对 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()

产出:

enter image description here

Tick _ params 对于设置 tick 属性非常有用。标签可以通过以下方式移动到顶部:

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