Python Pyplot - 自动将 x 轴范围设置为 min、max x 值传递给绘图函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17907977/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:27:03  来源:igfitidea点击:

Pyplot - automatically setting x axis range to min, max x values passed to plotting function

pythonmatplotlib

提问by Lamps1829

I'm creating a plot with a method similar to the following:

我正在使用类似于以下的方法创建一个图:

import pyplot as plt

for x_list in x_list_of_lists:
   plt.plot(y_list, x_list)

plt.show()

The range of the x axis seems to get set to the range of the first list of x values that is passed to plt.plot(). Is there a way to have pyplot automatically set the lower limit of the x axis to the lowest value in all of the x_list variables passed to it (plus a bit of leeway), and to have it do the same for the upper limit, using the highest x value passed to plot (plus a bit of leeway)? Thank you.

x 轴的范围似乎设置为传递给 plt.plot() 的第一个 x 值列表的范围。有没有办法让 pyplot 自动将 x 轴的下限设置为传递给它的所有 x_list 变量中的最小值(加上一点余地),并让它对上限做同样的事情,使用传递给 plot 的最高 x 值(加上一点余地)?谢谢你。

采纳答案by unutbu

Confusingly, your y_listcontains the values being plotted along the x-axis. If you want matplotlib to use values from x_listas x-coordinates, then you should call

令人困惑的是,您y_list包含沿x-axis. 如果您希望 matplotlib 使用x_listas 中的值x-coordinates,那么您应该调用

plt.plot(x_list, y_list)

Maybe this is the root of your problem. By default matplotlib sets the xand ylimits big enough to include all the data plotted.

也许这就是你问题的根源。默认情况下,matplotlib 设置xy限制足够大以包含所有绘制的数据。

So with this change, matplotlib will now be using x_listas x-coordinates, and will automatically set the limits of the x-axisto be wide enough to display all the x-coordinatesspecified in x_list_of_lists.

所以这种变化,现在matplotlib将使用x_listx-coordinates,并会自动设定的限度x-axis是足够宽,以显示所有的x-coordinates规定x_list_of_lists



However, if you wish to adjust the xlimits, you could use the plt.xlim function.

但是,如果您希望调整x限制,您可以使用plt.xlim 函数

So, to set the lower limit of the x-axisto the lowest value in all of the x_listvariables (and similarly for the upper limit), you'd do this:

因此,要将 的下限设置为x-axis所有x_list变量中的最小值(对于上限也是如此),您可以这样做:

xmin = min([min(x_list) for x_list in x_list_of_lists])-delta
xmax = max([max(x_list) for x_list in x_list_of_lists])+delta
plt.xlim(xmin, xmax)

Make sure you place this afterall the calls to plt.plotand (of course) before plt.show().

确保你把此之后所有的调用plt.plot和之前(当然)plt.show()