Reputation: 23
I'm trying to plot time series data in matplotlib using a for loop. The goal is to dynamically plot 'n' years worth of daily closing price data. If i load 7 years of data, I get 7 unique plots. I have created a summary of the start and end dates for a data set, yearly_date_ranges (date is the index). I use this to populate start and end dates. The code I've written so far produces 7 plots of all daily data instead of 7 unique plots, one for each year. Any help is appreciated. Thanks in advance!
yearly_date_ranges
start end
Date
2014 2014-04-01 2014-12-31
2015 2015-01-01 2015-12-31
2016 2016-01-01 2016-12-31
2017 2017-01-01 2017-12-31
2018 2018-01-01 2018-12-31
2019 2019-01-01 2019-12-31
2020 2020-01-01 2020-05-28
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
fig = plt.figure(figsize=(12,20))
for i in range(len(yearly_date_ranges)):
ax = fig.add_subplot(len(yearly_date_ranges),1,i + 1)
for row in yearly_date_ranges.itertuples(index=False):
start = row.start
end = row.end
subset = data[start:end]
ax.plot(subset['Close'])
plt.show()
Upvotes: 0
Views: 70
Reputation: 23
This worked! Thank you for the help
fig, axes = plt.subplots(7,1, figsize=(12,20))
years = data.index.year
for ax, (k,d) in zip(axes.ravel(), data['Close'].groupby(years)):
d.plot(x='Close', ax=ax)
Upvotes: 0
Reputation: 150785
Dynamically you should do something like this:
fig, axes = plt.subplots(7,1, figsize=(12,20))
years = data.index.year
for ax, (k,d) in zip(axes.ravel(), data.groupby(years)):
d.plot(y='Close', ax=ax)
Upvotes: 0