使用 matplotlib 将 y 范围更改为从0开始

我正在使用 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)

这显示了一条从10到30的 y 轴曲线。虽然我对 x 范围很满意,但是我想将 y 范围改为从0开始,并在 ymax 上进行调整以显示所有内容。

我目前的解决办法是:

ax.set_ylim(0, max(ydata))

但是我想知道是否有一种方法可以说: autoscale 但是从0开始。

165432 次浏览

The range must be set after the plot.

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)

If ymin is changed before plotting, this will result in a range of [0, 1].

Edit: the ymin argument has been replaced by bottom:

ax.set_ylim(bottom=0)

Documentation: https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.set_ylim.html

You can do the same on the x axis with left and right:

ax.set_xlim(left=0)

Documentation: https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.set_xlim.html

Try this

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()

doc string as following:

>>> 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.

Note that ymin will be removed in Matplotlib 3.2 Matplotlib 3.0.2 documentation. Use bottom instead:

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)