提问人:Jason Sundram 提问时间:1/19/2013 最后编辑:CommunityJason Sundram 更新时间:3/30/2020 访问量:176876
在 matplotlib 中将 x 轴移动到绘图的顶部
Moving x-axis to the top of a plot in matplotlib
问:
基于这个关于 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(如上所述)似乎没有达到预期的效果。这是我的输出:
我做错了什么?
答:
49赞
Lev Levitsky
1/19/2013
#1
你想要set_ticks_position
而不是:set_label_position
ax.xaxis.set_ticks_position('top') # the rest is the same
这给了我:
233赞
unutbu
1/19/2013
#2
用
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()
1赞
user1420304
5/3/2013
#3
如果你想让蜱虫(不是标签)出现在顶部和底部(而不仅仅是顶部),你必须做一些额外的按摩。我能做到这一点的唯一方法是对 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()
输出:
25赞
wSmit
10/3/2013
#4
tick_params对于设置即时报价属性非常有用。标签可以通过以下方式移动到顶部:
ax.tick_params(labelbottom=False,labeltop=True)
评论
0赞
Milo Wielondek
10/8/2019
Kwargs 是布尔值,所以应该是 和 分别,否则工作完美!False
True
0赞
Josh
12/11/2023
#5
对于正在搜索顶级标签但以我开头并且不想切换到我的人,那么,从这两行开始绘图:plt
ax
plt.rcParams['xtick.bottom'] = plt.rcParams['xtick.labelbottom'] = False
plt.rcParams['xtick.top'] = plt.rcParams['xtick.labeltop'] = True
评论