如何设置'auto'作为上限,但使用matplotlib.pyplot保持固定的下限

vie*_*tee 99 python matplotlib

我想将y轴的上限设置为'auto',但我想保持y轴的下限始终为零.我试过'auto'和'autorange',但那些似乎不起作用.先感谢您.

这是我的代码:

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')
Run Code Online (Sandbox Code Playgroud)

eca*_*mur 91

您可以通过只leftrightset_xlim:

plt.gca().set_xlim(left=0)
Run Code Online (Sandbox Code Playgroud)

对于y轴,使用bottomtop:

plt.gca().set_ylim(bottom=0)
Run Code Online (Sandbox Code Playgroud)

  • 当我这样做时,上限会粘贴到窗口实例化的任何值.它不会保持自动缩放. (22认同)
  • 和@Elliot在这里一样的问题.可以通过在绘制值后设置(单侧)ylim/xlim来修复. (7认同)
  • 确保在绘制数据后设置限制,否则上限将默认为1。 (2认同)

sil*_*eto 36

只需设置xlim其中一个限制:

plt.xlim(xmin=0)
Run Code Online (Sandbox Code Playgroud)

  • 在Matplotlib 3.0中,不赞成使用xmin和xmax,而建议使用left和right。 (2认同)

小智 11

set_xlim允许set_ylimNone来实现这一点。但是,您必须在绘制数据使用这些函数。如果您不这样做,它将使用默认的 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()
Run Code Online (Sandbox Code Playgroud)

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


Rem*_*net 7

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

例如,

>>> ax.set_xlim(left_limit, right_limit)
>>> ax.set_xlim((left_limit, right_limit))
>>> ax.set_xlim(left=left_limit, right=right_limit)
Run Code Online (Sandbox Code Playgroud)

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

>>> 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)
Run Code Online (Sandbox Code Playgroud)

要设置当前轴的x限制,matplotlib.pyplot模块包含xlim仅包装matplotlib.pyplot.gca和的功能 matplotlib.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
Run Code Online (Sandbox Code Playgroud)

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


Sky*_*326 6

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