Skip to main content
 首页 » 编程设计

python之如何关闭 matplotlib 图的边界

2025年05月04日11xiaohuochai

我发现 pyplot 图有一个奇怪的行为。当数据点的数量超过一定数量时,线不会画到尽头——最右边有空白,我无法摆脱。我想知道如何强制 pyplot 一路绘制。

我正在使用 Python 2.7.5 和 matplotlib 1.2.1。

from pylab import * 
from random import random 
bins = arange(0, 180, 5) 
data = array([random() for i in xrange(len(bins))]) 
plot(bins[:10], data[:10], drawstyle="steps-mid") #draws till the end 
title("some data") 
figure() 
plot(bins, data, drawstyle="steps-mid") #white space at the right 
title("all data") 
show() 

其他事件的 drawstyle 选项也会发生这种情况。我可以在绘图后使用 xlim 来缩小 xaxis,这样被切断的部分也被切断了轴,但我不想这样做,因为我想保持我的轴不变这是。我考虑过向 bins 添加一个额外的元素,向 data 添加一个零,然后使用 xlim,但这让我觉得这是一个非常古怪的修复。

可以看到 all data 的图和 some data .

请您参考如下方法:

使用你的Axes' set_xlim()避免您所看到的自动调整范围行为的方法。

data = array([random() for i in xrange(len(bins))]) 
plot(bins[:10], data[:10], drawstyle="steps-mid") #draws till the end 
title("some data") 
 
fig = figure() 
ax = fig.add_subplot(111) 
plot(bins, data) 
ax.set_xlim(min(bins), max(bins) 
ax.set_title("all data") 
show()