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

标签 python matplotlib plot data-visualization

基于 this question about heatmaps in 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's set_label_position (如上所述)似乎没有达到预期的效果。这是我的输出:

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

关于python - 在 matplotlib 中将 x 轴移动到绘图的顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48470251/

相关文章:

python - 绘制 error_only size-1 数组可以转换为 Python 标量

python - 无法通过 Python 和 pymysql 插入 MySQL

Python/Flasks/Socketio,socketio.emit(...) 不发出

python - 如果值超过 matplotlib 中的 xlim,如何环绕绘图

python - 如何在Python中将多个直方图堆叠在一个图中?

r - 自定义 R 中 image.plot 中的颜色范围

python - 计算速度与属性入类

python - 在 if 语句中初始化的变量的范围是什么?

python - 如何在 matplotlib 中插入子图下方的文本?

python - 用 python 绘制数学数据