Skip to main content
 首页 » 编程设计

python之如何强制 pyplot 显示轴限制

2025年05月04日10insus

我的 x 轴和 y 轴通常分别在 0 到 300 和 0 到 60 之间。

我只想显示 5 <= x <= 300 中的值,不过,我也是这样

ax.set_xlim(left=5) 

之后图形确实从 5 开始,但没有任何迹象表明这一点。我在 x 轴上的第一个刻度是 50,然后是 100、150...y 轴上的刻度标记为 0、20、40、60,这很容易误导观众认为 0 的下限y轴也代表x轴的下限0。

我如何强制 pyplot 在 x=5 处显示一个额外的刻度,以便明确告知查看者两个轴的下限不相同?

请您参考如下方法:

您可以使用 xticks 设置 x 轴的刻度。 这是一个 ipython session :

In [18]: l = [random.randint(0, 10) for i in range(300)] 
 
In [19]: plot(l) 
Out[19]: [<matplotlib.lines.Line2D at 0x9241f60>] 
 
In [20]: plt.xlim(xmin=5)       # I set to start at 5. No label is draw 
Out[20]: (5, 300.0) 
 
In [21]: plt.xticks(arange(5, 301, 50))  # this makes the first xtick at left to be 5 
                                         # note the max range is 301, otherwise you will never 
                                         # get 300 even if you set the appropriate step 

请注意,现在 x 轴的右侧没有标签。最后一个标签是 255(与您在左侧遇到的问题相同)。您可以获得此标签,修改排列的步长,以便 max - min/step 成为(或非常接近)整数值(刻度数)。

这样就可以了(尽管十进制数很难看):

In [38]: plt.xticks(arange(5, 301, 29.5))