Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib: Plot Data and then Time Series Predictions

I'm using matplotlib to display a stock's price movements over time. I want to focus on the last 90 days and then predict the next 14 days. I have the last 90 days of data and my predictions, but I want to graph my predictions in a different color, so it's clear they're different.

How would I do this?

If I just add a second plot() call to my code, the predictions will start from the same point as my 90 days of data and be overlaid, which isn't what I want.

Right now I'm doing this:

df[-90:]["price"].plot()
plt.show()

Thanks!

like image 716
anon_swe Avatar asked Aug 19 '26 05:08

anon_swe


1 Answers

Hopefully this is what you want:

import pandas as pd
import numpy as np; np.random.seed(1)
import matplotlib.pyplot as plt

datelist = pd.date_range(pd.datetime(2018, 1, 1), periods=104)
df = pd.DataFrame(np.cumsum(np.random.randn(104)), 
                  columns=['price'], index=datelist)

plt.plot(df[:90].index, df[:90].values)
plt.plot(df[90:].index, df[90:].values)
# If you don't like the break in the graph, change 90 to 89 in the above line
plt.gcf().autofmt_xdate()
plt.show()

enter image description here

like image 163
Y. Luo Avatar answered Aug 21 '26 17:08

Y. Luo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!