Saturday, 21 December 2019

matplotlib date plot

import pandas as pd
from datetime import datetime, timedelta
from matplotlib import pyplot as plt
#from matplotlib import dates as mpl_dates

dates = [
    datetime(2019, 5, 24),
    datetime(2019, 5, 25),
    datetime(2019, 5, 26),
    datetime(2019, 5, 27),
    datetime(2019, 5, 28),
    datetime(2019, 5, 29),
    datetime(2019, 5, 30),
]

y = [0, 1, 3, 4, 6, 5, 7]

plt.plot_date(dates, y, linestyle='solid')
plt.gcf().autofmt_xdate()


dates = [
    datetime(2019, 5, 24),
    datetime(2019, 5, 25),
    datetime(2019, 5, 26),
    datetime(2019, 5, 27),
    datetime(2019, 5, 28),
    datetime(2019, 5, 29),
    datetime(2019, 5, 30),
    datetime(2019, 5, 23),
]
if time series is not sorted

import pandas as pd
from datetime import datetime, timedelta
from matplotlib import pyplot as plt
import pandas as pd

dates = [
    datetime(2019, 5, 24),
    datetime(2019, 5, 25),
    datetime(2019, 5, 26),
    datetime(2019, 5, 27),
    datetime(2019, 5, 28),
    datetime(2019, 5, 29),
    datetime(2019, 5, 30),
    datetime(2019, 5, 23),
]

y = [0, 1, 3, 4, 6, 5, 7, 1]

data = pd.DataFrame({'Dates': dates, 'Price': y})
print data
data.sort_values('Dates', inplace=True)
print data

plt.plot_date(data['Dates'], data['Price'], linestyle='solid')
plt.gcf().autofmt_xdate()

       Dates  Price
0 2019-05-24      0
1 2019-05-25      1
2 2019-05-26      3
3 2019-05-27      4
4 2019-05-28      6
5 2019-05-29      5
6 2019-05-30      7
7 2019-05-23      1
       Dates  Price
7 2019-05-23      1
0 2019-05-24      0
1 2019-05-25      1
2 2019-05-26      3
3 2019-05-27      4
4 2019-05-28      6
5 2019-05-29      5
6 2019-05-30      7
dates are sorted

reference:
https://www.youtube.com/watch?v=_LWjaAiKaf8&list=PL-osiE80TeTvipOqomVEeZ1HRrcEvtZB_&index=8
https://stackoverflow.com/questions/28503445/assigning-column-names-to-a-pandas-series

No comments:

Post a Comment