Reputation: 1485
I am struggling to plot a simple time series with seaborn and can't understand why this hasn't work. My dataframe time_series
give daily data for patients from 2015 to 2019 and also has a datetime
index.It looks as such:
patients
Date
2015-01-04 49
2015-01-05 51
2015-01-06 48
2015-01-07 30
2015-01-08 27
I am trying to build a scatter plot, however upon building it, it starts at 2000 and therefore all the data points are to the right of the graph. I tried to counter this by setting an xlim
but am receiving a strange error. My code is as such:
import seaborn as sns
import matplotlib.pyplot as plt
sns.scatterplot(x=time_series.index, y=time_series['patients'])
plt.xlim(2015,2019)
This is the error which I don't understand as I have no year '0':
ValueError: year 0 is out of range
Can anyone help me out here. Many Thanks
Upvotes: 1
Views: 3459
Reputation: 62403
datetime
information from the df.index
is converted to a datetime ordinal representation for the plot locs
.locs, labels = plt.xticks()
, comment out plt.xlim
and print locs
, you will see they are array([729390.00000485, 730120.00000485, 730851.00000485, 731581.00000485, 732312.00000485, 733042.00000485, 733773.00000485, 734503.00000485, 735234.00000485, 735964.00000485])
. So when you set plt.xlim(2015, 2019)
you are not in the range of the locs
being plotted. The years are just labels.from datetime import date, datetime
# determine ordinal value for desired date range
print(date.toordinal(datetime(2015, 1, 1, 0, 0)))
>>>735599
print(date.toordinal(datetime(2019, 1, 1, 0, 0)))
>>>737060
chart = sns.scatterplot(x=df.index, y=df['patients'])
plt.xlim(735599, 737060)
plt.setp(chart.get_xticklabels(), rotation=45)
plt.show()
Upvotes: 1