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

时间:2014-03-25 17:51:18

标签: python matplotlib

我正在使用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开始改变并调整ymax以显示所有内容

我目前的解决方案是:

ax.set_ylim(0, max(ydata))

但是我想知道是否有办法说:autoscale但是从0开始。

3 个答案:

答案 0 :(得分:53)

必须在>之后设置范围。

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)

答案 1 :(得分:20)

试试这个

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如下:

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

答案 2 :(得分:3)

请注意,ymin将在Matplotlib 3.2 Matplotlib 3.0.2 documentation中删除。 请改用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)