python - 更改 imshow 或类似函数的单元格大小/宽度

标签 python matplotlib plot imshow

我需要第一个和最后一个单元格的宽度为一半。

我的目标是得到这样的东西:

enter image description here

但是我得到了这个:

enter image description here

我的代码:

import numpy as np
import matplotlib.pyplot as plt

data = np.array([0.    , 0.2   , 0.4   , 0.6   , 0.8   , 1.    ])
fig, ax = plt.subplots()
matrix = data.reshape(1, -1)
ax.imshow(matrix, cmap='hot')
plt.show()

有办法做到这一点吗?

最佳答案

正如乔迪评论的那样,如果您只想剪切最外面的单元格,一个快速的快捷方式是更改轴限制:

ax.set_xlim(0, 5)

但在更一般的情况下,请使用 pcolormesh用于自定义网格。定义xy单元边界并在该自定义网格上绘制矩阵:

import numpy as np
import matplotlib.pyplot as plt

data = np.linspace(0, 1, 6)
matrix = data.reshape(1, -1)

# define cell bounds
x = [0, 0.5, 1.5, 2.5, 3.5, 4.5, 5]
y = [-0.5, 0.5]

# plot matrix on custom mesh
fig, ax = plt.subplots()
ax.pcolormesh(x, y, matrix, cmap='hot')

# restyle like imshow
ax.set_aspect('equal')
ax.invert_yaxis()

plt.show()

或者采用更具编程性的方式来定义边界:

r, c = matrix.shape

x = np.arange(c + 1) - 0.5  # [-0.5  0.5  1.5  2.5  3.5  4.5  5.5]
x[0] += 0.5                 # [ 0.   0.5  1.5  2.5  3.5  4.5  5.5]
x[-1] -= 0.5                # [ 0.   0.5  1.5  2.5  3.5  4.5  5. ]

y = np.arange(r + 1) - 0.5  # [-0.5  0.5]

关于python - 更改 imshow 或类似函数的单元格大小/宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75968670/

相关文章:

python - 防止 SIGQUIT 终止交互式 python

c++ - 如何使用 Python 绑定(bind)到 Clang 解析单个文件?

python - Matplotlib : display array values with imshow

Python Pandas : How to split a column on left parenthesis and remove numbers from a column of dataframe

python - PIL(低)和多页 TIFFS

r - R中绘图的坐标

java - jfreechart:如何排列两个图?

r - 在图中显示 "for all"(∀) 符号

python - 为什么 matplotlib 将我的圆圈绘制为椭圆?

python - 如何使用python从csv文件创建饼图