如何使用 pyplot 自动(或手动)缩放 xticks 和 yticks?

How to have automatic (or manual) scaling of xticks and yticks with pyplot?

基本上,我希望我的曲线能够正确地拟合到图表上,因为目前显然不是这种情况。根据 pyplot,我的 xtick 间隔是相等的,但它们显然具有不匹配的值。我想让 pyplot 理解这一点,但我不确定为什么当曲线有足够的 space 时它会强制曲线在方图中成为 'boxed'... 我做错了什么?

这是我当前创建情节的代码。

plt.figure(sheet_name, figsize=(12, 6))
plt.plot(beam_deformation, '-x')
plt.xticks([sensor[0] for sensor in sensors], [f"{sensor[0]} ({i+1})" for i, sensor in enumerate(sensors)], rotation=20)
plt.xlabel('sensors (position)')
plt.ylabel('Extent of Deformation (in)')

当您仅向 plt.plot 提供一个数组时,它会绘制在 x = [0, 1, 2, ...]:

x, y: The horizontal and vertical coordinates of the data points. x values are optional and default to range(len(y)).

因此在当前代码中,beam_deformation 被假定为 y 并绘制在 x = [0, 1, 2, ...] 处。然后刻度线设置为 [0.5, 2.9, 5.3, ...],但这与 beam_deformation 点的绘制方式无关。


要在 x = [0.5, 2.9, 5.3, ...] 绘制 beam_deformation 点,将 x 值显式传递给 plt.plot:

x = [float(s[0]) for s in sensors]   # x = [0.5, 2.9, 5.3, ...]
plt.plot(x, beam_deformation, '-x')  # explicitly set x coordinates

plt.xticks(x, [f'{s[0]} ({i+1})' for i, s in enumerate(sensors)], rotation=20)

或者如果您确实想在 x = [0, 1, 2, ...] 处绘制 beam_deformation,则相应地设置刻度位置:

plt.plot(beam_deformation, '-x')     # assume x = [0, 1, 2, ...]

ticks = range(len(beam_deformation)) # since x = [0, 1, 2, ...]
labels = [f'{s[0]} ({i+1})' for i, s in enumerate(sensors)]
plt.xticks(ticks, labels, rotation=20)

在这种情况下,由于您的传感器值都是等距的(相距 2.4),因此两个版本最终在视觉上看起来是一样的: