将matplotlib的y范围改为从0开始

95 投票
4 回答
210481 浏览
提问于 2025-04-17 23:51

我正在使用matplotlib来绘制数据。这里有一段代码可以做类似的事情:

import matplotlib.pyplot as plt
f, ax = plt.subplots(1)
xdata = [1, 4, 8]
ydata = [10, 20, 30]
ax.plot(xdata, ydata)
plt.show(f)

这段代码在图表中显示了一条线,y轴的范围是从10到30。虽然我对x轴的范围很满意,但我想把y轴的范围改成从0开始,并且调整y轴的最大值,以便能显示所有的数据。

我现在的解决办法是这样做:

ax.set_ylim(0, max(ydata))

不过我在想,有没有办法直接设置为自动缩放,但y轴从0开始呢?

4 个回答

1

下面的代码确保在图表中始终显示y值为0:

import numpy as np
import matplotlib.pyplot as plt
xdata = np.array([1, 4, 8])
ydata = np.array[10, 20, 30])
plt.plot(xdata, ydata)
plt.yticks(np.arange(min(0, min(xdata)), max(0, max(xdata)), 5))
plt.show()

它也适用于只有负数的y数据值。最后一个参数(刻度步长)可以省略。

14

请注意,ymin 在 Matplotlib 3.2 版本中将会被移除,详细信息可以查看 Matplotlib 3.0.2 的文档。请使用 bottom 来代替:

import matplotlib.pyplot as plt
f, ax = plt.subplots(1)
xdata = [1, 4, 8]
ydata = [10, 20, 30]
ax.plot(xdata, ydata)
ax.set_ylim(bottom=0)
plt.show(f)
63

试试这个

import matplotlib.pyplot as plt
xdata = [1, 4, 8]
ydata = [10, 20, 30]
plt.plot(xdata, ydata)
plt.ylim(ymin=0)  # this line
plt.show()

文档字符串如下:

>>> help(plt.ylim)
Help on function ylim in module matplotlib.pyplot:

ylim(*args, **kwargs)
    Get or set the *y*-limits of the current axes.

    ::

      ymin, ymax = ylim()   # return the current ylim
      ylim( (ymin, ymax) )  # set the ylim to ymin, ymax
      ylim( ymin, ymax )    # set the ylim to ymin, ymax

    If you do not specify args, you can pass the *ymin* and *ymax* as
    kwargs, e.g.::

      ylim(ymax=3) # adjust the max leaving min unchanged
      ylim(ymin=1) # adjust the min leaving max unchanged

    Setting limits turns autoscaling off for the y-axis.

    The new axis limits are returned as a length 2 tuple.
155

范围必须在绘图之后设置。

import matplotlib.pyplot as plt
f, ax = plt.subplots(1)
xdata = [1, 4, 8]
ydata = [10, 20, 30]
ax.plot(xdata, ydata)
ax.set_ylim(ymin=0)
plt.show(f)

如果在绘图之前更改了ymin,那么范围将会是[0, 1]。

补充说明:ymin参数已经被bottom替代:

ax.set_ylim(bottom=0)

文档链接:https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.set_ylim.html

你也可以用左边和右边来对x轴做同样的设置:

ax.set_xlim(left=0)

文档链接:https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.set_xlim.html

撰写回答