Python 使用 matplotlib 将 y 范围更改为从 0 开始
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22642511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change y range to start from 0 with matplotlib
提问by Maxime Chéramy
I am using matplotlib to plot data. Here's a code that does something similar:
我正在使用 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)
This shows a line in a graph with the y axis that goes from 10 to 30. While I am satisfied with the x range, I would like to change the y range to start from 0 and adjust on the ymax to show everything.
这在图中显示了一条线,y 轴从 10 到 30。虽然我对 x 范围感到满意,但我想将 y 范围更改为从 0 开始并在 ymax 上进行调整以显示所有内容。
My current solution is to do:
我目前的解决方案是:
ax.set_ylim(0, max(ydata))
However I am wondering if there is a way to just say: autoscale but starts from 0.
但是我想知道是否有一种方法可以说:自动缩放但从 0 开始。
采纳答案by Maxime Chéramy
The range must be set afterthe 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 yminis changed before plotting, this will result in a range of [0, 1].
如果ymin在绘图之前更改,这将导致 [0, 1] 的范围。
Edit: the yminargument has been replaced by bottom:
编辑:该ymin参数已被替换为bottom:
ax.set_ylim(bottom=0)
回答by WeizhongTu
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.
回答by Sam Sirmaxford
Note that yminwill be removed in Matplotlib 3.2 Matplotlib 3.0.2 documentation.
Use bottominstead:
请注意,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)

![Python IOError: [Errno 22] 无效模式 ('wb') 或文件名:](/res/img/loading.gif)