如何强制pyplot显示轴限制

时间:2012-11-29 19:00:15

标签: python matplotlib axes

我的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处显示额外的刻度,以便明确告知观察者两个轴的下限不同于0?

1 个答案:

答案 0 :(得分:1)

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

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

请注意,现在,在xaxis的右侧,没有标签。最后一个标签是255(与左侧相同的问题)。您可以使用此标签修改arange的步骤,以使max - min / step成为(或非常接近)整数值(刻度数)。

这使得它(尽管十进制数字很难看):

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