Изменение диапазона y для начала с 0 с помощью 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.

Ответы

Ответ 1

Диапазон должен быть установлен после сюжета.

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)

Ответ 2

Попробуйте это

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 строка:

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

Ответ 3

Обратите внимание, что 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)