要设置matplotlib图表比例,使其不会随着线的增长而改变,可以使用plt.axis()
函数来控制图表的坐标轴范围。具体步骤如下:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
line = ax.plot(x, y)
x_min, x_max = min(x), max(x)
y_min, y_max = min(y), max(y)
ax.axis([x_min, x_max, y_min, y_max])
完整的代码示例:
import matplotlib.pyplot as plt
# 创建图表对象
fig, ax = plt.subplots()
# 绘制线条并获取数据范围
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
line = ax.plot(x, y)
x_min, x_max = min(x), max(x)
y_min, y_max = min(y), max(y)
# 设置坐标轴范围
ax.axis([x_min, x_max, y_min, y_max])
# 显示图表
plt.show()
这样设置后,无论线的增长如何,图表的比例都会保持不变。
领取专属 10元无门槛券
手把手带您无忧上云