使热图具有相同的轴大小

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

这是示例代码。在这里,

xlim = (0,2)
ylim = (0,5)
。我想保持这种方式(不同的限制),同时找出一种使 x 轴和 y 轴大小相同的方法。

import matplotlib.pyplot as plt
import numpy as np

# Create a heatmap dataset.
x = np.linspace(0, 2, 100)
y = np.linspace(0, 5, 100)
Z = np.random.rand(100, 100)

# Create a figure and axes object.
fig, ax = plt.subplots()

# Set the x-limits to 2
ax.set_xlim([0, 2])

# Plot the heatmap.
im = ax.imshow(Z, extent=[0, 2, 0, 5])

# Set the labels and title.
ax.set_xlabel('X-Axis')
ax.set_ylabel('Y-Axis')
ax.set_title('Heatmap with Custom X-Limits')

# Show the plot.
plt.show()

结果:

我尝试使用

ax.set_box_aspect(1)
。这使得图形成为一个等轴的正方形,但是,将热图设置在中间,同时在两侧留下空白。

python matplotlib heatmap
1个回答
0
投票

由于您的数据不是图像,因此您应该使用

pcolormesh
,它允许您设置 x 轴和 y 轴。然后,
ax.set_box_aspect(1)
就可以正常工作了。

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2, 100)
y = np.linspace(0, 5, 100)
Z = np.random.rand(100, 100)

fig, ax = plt.subplots()

p = ax.pcolormesh(x, y, Z)
ax.set_box_aspect(1)
fig.show()

© www.soinside.com 2019 - 2024. All rights reserved.