当纵横比固定时,奇怪的 matplotlib 限制

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

当保留相等的纵横比时,我面临着 matplotlib 的奇怪行为。 对于初学者来说,这是展示此行为的最小代码示例。首先是正确的行为,其次是不正当的行为

import matplotlib.pyplot as plt
import numpy as np

# Generate some random data
x = np.arange(0, 10, 0.1)
y = np.random.randn(len(x))

# Create a plot
fig, ax = plt.subplots()

# ax.set_aspect('equal', 'datalim')
# Set x-axis limits
ax.set_xlim(2, 5)

# Print the x and y limits
print(f"x-axis limits before plotting: {ax.get_xlim()}")
print(f"y-axis limits before plotting: {ax.get_ylim()}")

ax.plot(x, y*10)


# Print the x and y limits
print(f"x-axis limits after plotting: {ax.get_xlim()}")
print(f"y-axis limits after plotting: {ax.get_ylim()}")

# Set x-axis limits
ax.set_xlim(2, 5)

# Print the x and y limits
print(f"x-axis limits after setting xlim: {ax.get_xlim()}")
print(f"y-axis limits after setting xlim: {ax.get_ylim()}")

# Show the plot
plt.show()

所以打印出来了

x-axis limits before plotting: (2.0, 5.0)
y-axis limits before plotting: (0.0, 1.0)
x-axis limits after plotting: (2.0, 5.0)
y-axis limits after plotting: (-23.30742047433786, 21.093948480431905)
x-axis limits after setting xlim: (2.0, 5.0)
y-axis limits after setting xlim: (-23.30742047433786, 21.093948480431905)

正确对应正在生成的图 enter image description here

现在,当我取消注释 ax.set_aspect('equal', 'datalim') 行时,奇怪的事情发生了。

打印以下数据

x-axis limits before plotting: (2.0, 5.0)
y-axis limits before plotting: (0.0, 1.0)
x-axis limits after plotting: (2.0, 5.0)
y-axis limits after plotting: (-31.012258207723225, 22.633044899779353)
x-axis limits after setting xlim: (2.0, 5.0)
y-axis limits after setting xlim: (-31.012258207723225, 22.633044899779353)

但是显示了一个具有完全不同限制的图表 enter image description here

我的问题是:

  1. 有没有办法让 matplotlib 返回正确的 x,y 限制
  2. 是否有办法通过仅更改 y 数据限制来保持 AR 不变,而手动设置 x 限制不变?
python matplotlib aspect-ratio
1个回答
0
投票

当您将纵横比设置为 'equal', 'datalim' 时,matplotlib 将创建一个图形,使得沿 y 轴一个单位的线段与沿 y 轴的线段大小相同。 x 轴 1 个单位。由于 y 轴上的值范围约为 x 轴上值范围的 10 倍,因此图表看起来应该是这样的。

如果你真的想保持纵横比,你可以调整图形大小

fig, ax = plt.subplots(figsize=(2, 20))

这将删除图表左侧和右侧多余的空白。您可以调整大小,使其缩放比例与数据集的限制(最小值/最大值)类似。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.