假设我有一定数量的数据集要一起绘制。
然后我想放大某个部分(例如,使用 ax.set_xlim
,或 plt.xlim
或 plt.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)
哪个生成
正如您所看到的,由于 y 轴一直使用与非限制版本相同的范围,因此下图很难看到某些东西。
我曾尝试使用 relim
、autoscale
或 autoscale_view
,但是没有用。对于单个数据集,我可以将 ylim
与该数据集的最小值和最大值一起使用。但对于不同的数据集,我必须查看所有数据。
是否有更好的方法来强制重新计算 y 轴范围?
答案 0 :(得分:1)
data_x
和xlim_min
创建一个xlim_max
的布尔掩码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)
ylim
和 xlim
,而是执行 x_vals = data_x[x_mask]
,然后使用 x_vals
和 y_vals
绘制 y2_vals
,这将删除 5代码行。
# 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)