如何在限制x轴后自动设置y轴限制

cle*_*enn 5 python numpy matplotlib python-3.x

假设我有一定数量的数据集想要一起绘制。

然后我想放大某个部分(例如,使用ax.set_xlim、 或plt.xlimplt.axis)。当我这样做时,它仍然保留缩放之前的计算范围。我怎样才能让它重新缩放到当前显示的内容?

例如,使用

import matplotlib
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

data_x = [d for d in range(100)]
data_y = [2*d for d in range(100)]
data_y2 = [(d-50)*(d-50) for d in range(100)]

fig = plt.figure(constrained_layout=True)
gs = gridspec.GridSpec(2, 1, figure=fig)

ax1 = fig.add_subplot(gs[0, 0])
ax1.grid()
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.scatter(data_x, data_y, s=0.5)
ax1.scatter(data_x, data_y2, s=0.5)

ax2 = fig.add_subplot(gs[1, 0])
ax2.grid()
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.scatter(data_x, data_y, s=0.5)
ax2.scatter(data_x, data_y2, s=0.5)
ax2.set_xlim(35,45)

fig.savefig('scaling.png', dpi=300)
plt.close(fig)
Run Code Online (Sandbox Code Playgroud)

哪个生成

变焦失败

正如您所看到的,由于 y 轴始终使用与非限制版本相同的范围,因此下面的图很难看到某些内容。

我尝试过使用relim,autoscale或者autoscale_view但那不起作用。对于单个数据集,我可以使用ylim该数据集的最小值和最大值。但对于不同的数据集,我必须仔细查看所有数据。

有没有更好的方法来强制重新计算 y 轴范围?

Tre*_*ney 2

  • 将列表转换为 numpy 数组
    • data_x创建一个基于xlim_min和 的布尔掩码xlim_max
    • 使用掩码选择y数据中的相关数据点
    • 合并两个选定的 y 数组
    • 从选定的 y 值中选择最小值和最大值并将它们设置为ylim
import numpy as np
import matplotlib.pyplot as plt

# use a variable for the xlim limits
xlim_min = 35
xlim_max = 45

# convert lists to arrays
data_x = np.array(data_x)
data_y = np.array(data_y)
data_y2 = np.array(data_y2)

# create a mask for the values to be plotted based on the xlims
x_mask = (data_x >= xlim_min) & (data_x <= xlim_max)

# use the mask on y arrays
y2_vals = data_y2[x_mask]
y_vals = data_y[x_mask]

# combine y arrays
y_all = np.concatenate((y2_vals, y_vals))

# get min and max y
ylim_min = y_all.min()
ylim_max = y_all.max()

# other code from op
...

# use the values to set xlim and ylim
ax2.set_xlim(xlim_min, xlim_max)
ax2.set_ylim(ylim_min, ylim_max)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

# use a variable for the xlim limits
xlim_min = 35
xlim_max = 45

# convert lists to arrays
data_x = np.array(data_x)
data_y = np.array(data_y)
data_y2 = np.array(data_y2)

# create a mask for the values to be plotted based on the xlims
x_mask = (data_x >= xlim_min) & (data_x <= xlim_max)

# use the mask on x
x_vals = data_x[x_mask]

# use the mask on y
y2_vals = data_y2[x_mask]
y_vals = data_y[x_mask]

# other code from op
...

# plot
ax2.scatter(x_vals, y_vals, s=0.5)
ax2.scatter(x_vals, y2_vals, s=0.5)
Run Code Online (Sandbox Code Playgroud)