如何设置轴限制

问题描述 投票:0回答:10

我需要帮助设置 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))

根据该图的数据,我得到的 y 轴限制为 20 和 200。但是,我希望限制为 20 和 250。

python matplotlib yaxis x-axis
10个回答
956
投票

通过

plt.gca()
获取当前轴,然后设置其限制:

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

181
投票

您可以做的一件事是使用 matplotlib.pyplot.axis 自行设置轴范围。

matplotlib.pyplot.axis

from matplotlib import pyplot as plt
plt.axis([0, 10, 0, 20])

0,10 为 x 轴范围。 0,20 用于 y 轴范围。

或者您也可以使用 matplotlib.pyplot.xlim 或 matplotlib.pyplot.ylim

matplotlib.pyplot.ylim

plt.ylim(-2, 2)
plt.xlim(0,10)

154
投票

另一个解决方法是获取绘图的轴并重新分配,仅更改 y 值:

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

44
投票

您可以从

matplotlib.pyplot.axes
实例化一个对象并在其上调用
set_ylim()
。会是这样的:

import matplotlib.pyplot as plt
axes = plt.axes()
axes.set_ylim([0, 1])

43
投票

仅用于微调。如果只想设置轴的一个边界,而让另一个边界不变,可以选择以下一种或多种语句

plt.xlim(right=xmax) #xmax is your value
plt.xlim(left=xmin) #xmin is your value
plt.ylim(top=ymax) #ymax is your value
plt.ylim(bottom=ymin) #ymin is your value

查看 xlimylim

的文档

30
投票

这至少在 matplotlib 版本 2.2.2 中有效:

plt.axis([None, None, 0, 100])

这可能是一种很好的设置方式,例如仅设置 xmin 和 ymax 等。


18
投票

要添加@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)

当我想从默认绘图设置中缩小或放大一点时,我发现这特别有用。


12
投票

这应该有效。你的代码对我有用,就像对 Tamás 和 Manoj Govindan 一样。看来你可以尝试更新 Matplotlib。如果您无法更新 Matplotlib(例如,如果您没有足够的管理权限),也许使用不同的后端和

matplotlib.use()
可能会有所帮助。


3
投票

ylim
可以使用
Axes.set()
进行设置。事实上,可以通过
set()
设置一整套属性,例如刻度、刻度标签、标签、标题等(在 OP 中单独设置)。

ax = plt.gca()
ax.set(ylim=(20, 250), xlim=(0, 100))

话又说回来,

ylim
(和其他属性)也可以在
plt.subplot
实例中设置。对于OP中的情况,那就是

aPlot = plt.subplot(321, facecolor='w', title="Year 1", ylim=(20,250), xticks=paramValues, ylabel='Average Price', xlabel='Mark-up')
#                                                       ^^^^  <---- ylim here
plt.plot(paramValues, plotDataPrice[0], color='#340B8C', marker='o', ms=5, mfc='#EB1717');

要为多个子图设置

ylim
(和其他属性),请使用
plt.setp
。例如,如果我们在 OP 的代码中包含另外 2 个子图,并且想要为所有子图设置相同的属性,则一种方法如下:

import matplotlib.pyplot as plt
import random

plt.figure(1, figsize = (8.5,11))
plt.suptitle('plot title')
ax = []
paramValues = range(10)
for i in range(1, 4):
    aPlot = plt.subplot(3,2,i, title=f"Year {i}")
    ax.append(aPlot)
    aPlot.plot(paramValues, [random.randint(20,200) for _ in paramValues], color='#340B8C', marker='o', ms=5, mfc='#EB1717')
    aPlot.grid(True);

plt.setp(ax, ylim=(20,250), facecolor='w', xticks=paramValues, ylabel='Average Price', xlabel='Mark-up')
#            ^^^^  <---- ylim here
plt.tight_layout();

0
投票

我们可以使用

plt.xlim()
plt.ylim()
.

查看下面的代码以正确理解它。

x = np.array([1,2,5,4,8])
fig = plt.figure(figsize=(5,5))

plt.plot(x,x**2, label='Square', marker='*')
plt.plot(x,x**3, label='Cube', marker='o')
plt.xlim(1,20)
plt.ylim(1,600)
plt.legend()
plt.show()

输出如下图所示。

© www.soinside.com 2019 - 2024. All rights reserved.