更改 imshow 或类似功能的单元格大小/宽度

问题描述 投票:0回答:1

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

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

但是我得到了这个:

我的代码:

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

有这样做的选择吗?

python matplotlib imshow
1个回答
0
投票

对非矩形网格使用

pcolormesh
。定义
x
y
单元格边界并在该网格上绘制您的
matrix

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

y = np.arange(r + 1) - 0.5  # [-0.5  0.5]
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. ]
© www.soinside.com 2019 - 2024. All rights reserved.