繁体   English   中英

如何为上限设置“自动”,但使用 matplotlib.pyplot 保持固定的下限

[英]How to set 'auto' for upper limit, but keep a fixed lower limit with matplotlib.pyplot

我想将 y 轴的上限设置为“自动”,但我想保持 y 轴的下限始终为零。 我试过“自动”和“自动范围”,但这些似乎不起作用。 先感谢您。

这是我的代码:

import matplotlib.pyplot as plt

def plot(results_plt,title,filename):

    ############################
    # Plot results

    # mirror result table such that each parameter forms an own data array
    plt.cla()
    #print results_plt
    XY_results = []

    XY_results = zip( *results_plt)

    plt.plot(XY_results[0], XY_results[2], marker = ".")

    plt.title('%s' % (title) )
    plt.xlabel('Input Voltage [V]')
    plt.ylabel('Input Current [mA]')

    plt.grid(True)
    plt.xlim(3.0, 4.2)  #***I want to keep these values fixed"
    plt.ylim([0, 80]) #****CHANGE**** I want to change '80' to auto, but still keep 0 as the lower limit 
    plt.savefig(path+filename+'.png')

您可以将leftright传递给set_xlim

plt.gca().set_xlim(left=0)

对于 y 轴,使用bottomtop

plt.gca().set_ylim(bottom=0)

只需为以下限制之一设置xlim

plt.xlim(left=0)

如前所述,根据 matplotlib 文档,可以使用matplotlib.axes.Axes类的set_xlim方法设置给定轴ax的 x 限制。

例如,

>>> ax.set_xlim(left_limit, right_limit)
>>> ax.set_xlim((left_limit, right_limit))
>>> ax.set_xlim(left=left_limit, right=right_limit)

一个限制可以保持不变(例如左限制):

>>> ax.set_xlim((None, right_limit))
>>> ax.set_xlim(None, right_limit)
>>> ax.set_xlim(left=None, right=right_limit)
>>> ax.set_xlim(right=right_limit)

要设置当前轴的 x 限制, matplotlib.pyplot模块包含xlim函数,该函数仅包装matplotlib.pyplot.gcamatplotlib.axes.Axes.set_xlim

def xlim(*args, **kwargs):
    ax = gca()
    if not args and not kwargs:
        return ax.get_xlim()
    ret = ax.set_xlim(*args, **kwargs)
    return ret

同样,对于 y 限制,请使用matplotlib.axes.Axes.set_ylimmatplotlib.pyplot.ylim 关键字参数是topbottom

只需在@silvio 上添加一个点:如果您使用轴来绘制figure, ax1 = plt.subplots(1,2,1) 然后ax1.set_xlim(xmin = 0)也有效!

你也可以这样做:

ax.set_xlim((None,upper_limit))
ax.set_xlim((lower_limit,None))

如果您想使用 set(),这会很有帮助,它允许您一次设置多个参数:

ax.set(xlim=(None, 3e9), title='my_title', xlabel='my_x_label', ylabel='my_ylabel')

set_xlimset_ylim允许None值来实现这一点。 但是,您必须在绘制数据使用这些函数。 如果您不这样做,它将使用默认的 0 表示左/下和 1 表示上/右。 一旦您设置了限制,它不会在每次绘制新数据时重新计算“自动”限制。

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([0, 1, 4, 5], [3, 5, 6, 9])
ax.set_xlim(left=2, right=None)
ax.set_ylim(bottom=None, top=7)

plt.show()

(即,在上面的示例中,如果您在最后执行ax.plot(...) ,则不会产生预期的效果。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM