0
$\begingroup$

I'm creating a time series model in Python. I converted a int field that counted the days (1,2,3,4) to a datetime field using the following code:

from datetime import datetime, timedelta

start = datetime.strptime('2016-01-01', '%Y-%m-%d')

df['Day'] = [start + timedelta(x) for x in range(730)]

I checked and it worked. The first date starts with 01/01/2016. I checked the dtypes of my two columns. The Day column is a datetime64[ns], while the revenue columns is float64.

When I try to plot the following code, I get an error that says I'm receiving this error: ValueError: view limit minimum -36834.64916714945 is less than 1 and is an invalid Matplotlib date value. This often happens if you pass a non-datetime value to an axis that has datetime units. I'm a little confused as to what's causing this since my datatype on the day columns is a datetime.

rolling_mean = df.rolling(window = 12).mean()
rolling_std = df.rolling(window = 12).std()
plt.plot(df, color = 'blue', label = 'Original')
plt.plot(rolling_mean, color = 'red', label = 'Rolling Mean')
plt.plot(rolling_std, color = 'black', label = 'Rolling Std')
plt.legend(loc = 'best')
plt.title('Rolling Mean & Rolling Standard Deviation')
plt.show()
plt.close()
$\endgroup$
1
  • $\begingroup$ We'll need some sample data, and full traceback to which line the error occurs $\endgroup$
    – WBM
    Apr 19 at 12:26
1
$\begingroup$

I assume an arbitrary df like:

df = pd.DataFrame(np.random.rand(720, 3), columns=list('abc'))

pyplot.plot([...]) doc expects a x and y, but you didn't specify what the x should be. If we include x as datetime values and y as the desired mean or std values, then the code looks like:

start = datetime.strptime('2016-01-01', '%Y-%m-%d')

df['day'] = [start + timedelta(x) for x in range(720)]

rolling_mean = df.rolling(window = 12, on="day").mean()
rolling_std = df.rolling(window = 12, on="day").std()

colors=['olive', 'gold', 'green', 'red', 'black', 'blue', 'purple', 'coral', 'teal']
for idx in df.columns.drop('day'):
    plt.plot(df['day'], df[idx], color = np.random.choice(colors), label = 'Original')
    plt.plot(rolling_mean['day'], rolling_mean[idx], color = np.random.choice(colors), label = 'Rolling Mean ' + str(idx))
    plt.plot(rolling_std['day'], rolling_std[idx], color = np.random.choice(colors), label = 'Rolling Std ' + str(idx))
plt.legend(loc = 'best')
plt.title('Rolling Mean & Rolling Standard Deviation')
plt.show()
plt.close()

This will give you this rainbow-coloured plot (if you wish other colors, check here)

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.