这是示例代码。在这里,
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)
。这使得图形成为一个等轴的正方形,但是,将热图设置在中间,同时在两侧留下空白。
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()