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


111

基于关于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(如上所述)似乎没有达到预期的效果。这是我的输出:

在此处输入图片说明

我究竟做错了什么?

Answers:


150

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

在此处输入图片说明


您能告诉我如何将X轴放在B和C之间吗?我尝试了一整天但没有成功
DaniPaniz '16


16

tick_params对于设置刻度属性非常有用。可以使用以下命令将标签移到顶部:

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

Kwargs是布尔值,因此应该分别为FalseTrue,否则效果很好!
米洛·维隆德克

1

如果要让刻度(而不是标签)显示在顶部和底部(而不仅仅是顶部),则必须做一些额外的按摩。我可以做到的唯一方法是对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()

输出:

在此处输入图片说明


您能告诉我如何将X轴放在B和C之间吗?我尝试了一整天但没有成功
DaniPaniz '16
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.