matplotlib数据可在xlim范围之外访问

时间:2013-09-26 08:03:34

标签: python matplotlib

考虑以下代码

import matplotlib.pyplot         as plt
import numpy                     as np            

time=np.arange(-100,100,01)
val =np.sin(time/10.)

time=-1.0*time

plt.figure()
plt.plot(time,val)
plt.xlim([70,-70])
plt.savefig('test.pdf')

当我在inkscape中打开pdf时,我可以选择(使用F2)整个数据,它只是在指定的xlim区间之外不可见:

enter image description here

问题似乎是

time=-1.0*time

如果我省略这一行,一切都很完美......不知道为什么会这样。我经常需要这样的变换,因为我处理古气候数据,这些数据有时在公元前B.和A.D.分别。

我看到这种行为的问题是,原则上有人可以将数据提供到我想要显示的范围之外。

有人知道如何解决这个问题(除了绘图前的一个数组)?

我使用matplotlib 1.1.1rc2

1 个答案:

答案 0 :(得分:1)

根据您选择的限制绘图时,您可以屏蔽阵列。是的,这也需要更改代码,但可能没有您可能担心的那么广泛。这是您的示例的更新版本:

import matplotlib.pyplot         as plt
import numpy                     as np            

time=np.arange(-100,100,01)
val =np.sin(time/10.)

time=-1.0*time

plt.figure()

# store the x-limites in variables for easy multi-use
XMIN = -70.0
XMAX = 70.0

plt.plot(np.ma.masked_outside(time,XMIN,XMAX),val)
plt.xlim([XMIN,XMAX])

plt.savefig('test.pdf') 

关键更改是使用np.ma.masked_outside作为x - 轴值(注意:掩码中XMINXMAX的顺序 - 命令并不重要。) 这样,如果您想稍后使用其他部分,则无需更改数组time 当我使用inkscape进行检查时,没有突出显示图表之外的数据。