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

时间:2021-05-19 08:25:56

标签: python python-3.x numpy matplotlib

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

然后我想放大某个部分(例如,使用 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)

哪个生成

failed zoom

正如您所看到的,由于 y 轴一直使用与非限制版本相同的范围,因此下图很难看到某些东西。

我曾尝试使用 relimautoscaleautoscale_view,但是没有用。对于单个数据集,我可以将 ylim 与该数据集的最小值和最大值一起使用。但对于不同的数据集,我必须查看所有数据。

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

1 个答案:

答案 0 :(得分:1)

  • 将列表转换为 numpy 数组
    • 基于data_xxlim_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)

enter image description here

# 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)
相关问题