在matplotlib中设置y轴限制

我需要帮助设置matplotlib上的y轴限制。 这是我尝试的代码,失败。

import matplotlib.pyplot as plt plt.figure(1, figsize = (8.5,11)) plt.suptitle('plot title') ax = [] aPlot = plt.subplot(321, axisbg = 'w', title = "Year 1") ax.append(aPlot) plt.plot(paramValues,plotDataPrice[0], color = '#340B8C', marker = 'o', ms = 5, mfc = '#EB1717') plt.xticks(paramValues) plt.ylabel('Average Price') plt.xlabel('Mark-up') plt.grid(True) plt.ylim((25,250)) 

有了这个图的数据,我得到了20和200的y轴限制。然而,我想要限制20和250。

尝试这个 。 也适用于subplots。

 axes = plt.gca() axes.set_xlim([xmin,xmax]) axes.set_ylim([ymin,ymax]) 

你的代码也适用于我。 但是,另一个解决方法是获取图的坐标轴,然后只更改y值:

x1,x2,y1,y2 = plt.axis()
plt.axis((x1,x2,25,250))

这应该工作。 您的代码适用于我,例如Tamás和Manoj Govindan。 看起来你可以尝试更新Matplotlib。 如果你不能更新Matplotlib(例如,如果你没有足够的pipe理权限),也许使用不同的后端matplotlib.use()可以帮助。

要添加到@ Hima的答案,如果您想要修改当前的x或y限制,您可以使用以下内容。

 import numpy as np # you probably alredy do this so no extra overhead fig, axes = plt.subplot() axes.plot(data[:,0], data[:,1]) xlim = axes.get_xlim() # example of how to zoomout by a factor of 0.1 factor = 0.1 new_xlim = (xlim[0] + xlim[1])/2 + np.array((-0.5, 0.5)) * (xlim[1] - xlim[0]) * (1 + factor) axes.set_xlim(new_xlim) 

我觉得这个特别有用,当我想缩小或从默认绘图设置一点点放大。