Reputation: 1927
Recently I started learning Matplotlib. I wrote one of my code and saw that the output is weird. This is my code and below that the output of this code:
from matplotlib import pyplot as plt
import pandas as pd
plt.style.use('seaborn')
data = pd.read_csv('C:/py/matplotlib/08-TimeSeries/data.csv')
price_date = pd.to_datetime(data['Date'])
data.sort_values('Date', inplace=True)
price_close = data['Close']
plt.plot_date(price_date, price_close, linestyle='solid')
plt.gcf().autofmt_xdate()
plt.tight_layout()
plt.show()
this is the entire code and the output of the above code looks like this:
What am I doing wrong in there, I doubt price_date = pd.to_datetime(data['Date'])
this is why I am getting this error, but there could be other reasons. Can you please help with this?
Upvotes: 0
Views: 47
Reputation: 3082
You need to sort your data before you write your x-axis data (price_date).
To get the desired result replace
price_date = pd.to_datetime(data['Date'])
data.sort_values('Date', inplace=True)
price_close = data['Close']
with
data['Date'] = pd.to_datetime(data['Date'])
data.sort_values('Date', inplace=True)
price_date = data['Date']
price_close = data['Close']
Upvotes: 0
Reputation: 2696
You use price_date = pd.to_datetime(data['Date'])
for the x-axis and after that you sort data['Date']
. I guess this could be your problem (without actually knowing what your data looks like). Try:
from matplotlib import pyplot as plt
import pandas as pd
plt.style.use('seaborn')
data = pd.read_csv('C:/py/matplotlib/08-TimeSeries/data.csv')
data['Date'] = pd.to_datetime(data['Date']) # Just change the column itself to datetime
data.sort_values('Date', inplace=True)
price_close = data['Close'] # This is not actually necessary. You can just use date['Close'] in the plot_date below
plt.plot_date(data['Date'], data['Close'], linestyle='solid')
plt.gcf().autofmt_xdate()
plt.tight_layout()
plt.show()
Upvotes: 1