2017-06-06 160 views
0

如何使我的x軸爲不等間隔的日期來平滑繪圖。我的數據是;在x軸上使用不均勻的間隔平滑繪圖

import numpy as np 
from pylab import plt 
import datetime as dt 

x = np.array([dt.date(2000, 11, 30), dt.date(2001, 3, 31), dt.date(2001, 11, 30), 
       dt.date(2002, 3, 31), dt.date(2002, 11, 30), dt.date(2003, 3, 31), 
       dt.date(2003, 11, 30), dt.date(2004, 3, 31), dt.date(2004, 11, 30), 
       dt.date(2005, 3, 31), dt.date(2005, 11, 30), dt.date(2006, 3, 31), 
       dt.date(2006, 11, 30), dt.date(2007, 3, 31), dt.date(2007, 11, 30), 
       dt.date(2008, 3, 31), dt.date(2008, 11, 30), dt.date(2009, 3, 31), 
       dt.date(2009, 11, 30), dt.date(2010, 3, 31), dt.date(2010, 11, 30), 
       dt.date(2011, 3, 31), dt.date(2011, 11, 30), dt.date(2012, 3, 31), 
       dt.date(2012, 11, 30), dt.date(2013, 3, 31), dt.date(2013,11, 30)]) 

    y = np.array([0, -2.15881, -1.18881, -2.91211, -2.33211, -5.06131, -4.24131, -6.04321, -4.56321, -6.42431, -5.68431, -8.83711, -8.43711, -11.02821, 
        -10.66821, -12.90341, -11.02341, -13.77671, -13.27671, -13.89671, 
        -12.23671, -13.89411, -12.61411]) 

plt.plot(x, y) 

我試過scipy spline,但由於x間距不均勻而出現問題。

回答

1

它爲我工作!

您必須將日期轉換爲數字,並使用scipy.interplolate.spline使繪圖更平滑。

import numpy as np 
from pylab import plt 
import datetime as dt 
from scipy.interpolate import spline 
from matplotlib import dates 

x = np.array([dt.date(2000, 11, 30), dt.date(2001, 3, 31), dt.date(2001, 11, 30), 
       dt.date(2002, 3, 31), dt.date(2002, 11, 30), dt.date(2003, 3, 31), 
       dt.date(2003, 11, 30), dt.date(2004, 3, 31), dt.date(2004, 11, 30), 
       dt.date(2005, 3, 31), dt.date(2005, 11, 30), dt.date(2006, 3, 31), 
       dt.date(2006, 11, 30), dt.date(2007, 3, 31), dt.date(2007, 11, 30), 
       dt.date(2008, 3, 31), dt.date(2008, 11, 30), dt.date(2009, 3, 31), 
       dt.date(2009, 11, 30), dt.date(2010, 3, 31), dt.date(2010, 11, 30), 
       dt.date(2011, 3, 31), dt.date(2011, 11, 30)]) 

y = np.array([0, -2.15881, -1.18881, -2.91211, -2.33211, -5.06131, -4.24131, -6.04321, 
       -4.56321, -6.42431, -5.68431, -8.83711, -8.43711, -11.02821, 
       -10.66821, -12.90341, -11.02341, -13.77671, -13.27671, -13.89671, 
       -12.23671, -13.89411, -12.61411]) 

# create an array of numbers for the dates 
x_dates = np.array([dates.date2num(i) for i in x]) 

plt.figure() 
plt.plot(x, y) 
plt.show() 

# create more uniform intervals in x axis and use spline to interpolate data 
x_smooth = np.linspace(x_dates.min(), x_dates.max(), 200) 
y_smooth = spline(x_dates, y, x_smooth) 

# creating a new date array from the new date number array 
x_new = np.array([dates.num2date(i) for i in x_smooth]) 

plt.figure() 
plt.plot(x_new, y_smooth) 
plt.show() 

所以,最初的數字是:Original Figure

新的數字是:Interpolated figure

並且重疊兩個數字,我們看到,與之匹配的是相當不錯的! Superimposing both the plots