Reputation: 1378
I want to create a bar chart where the x-axis
represents months and the height of the bars are proportional to the amount of days entered into a list of dates that fall in this month. I want to dynamically update the list and the program should then update the graph as this list is extended.
I am able to create a list of dates as follows:
import matplotlib.pyplot as plt
import datetime
dates = [datetime.date(2015,01,05),
datetime.date(2015,01,18),
datetime.date(2015,01,25),
datetime.date(2015,02,18),
datetime.date(2015,03,07),
datetime.date(2015,03,27),]
If I run the script I would like to see something like:
Which I plotted here manually.
I know it will be possible to use a loop to run through the list of dates and manually sum the dates using if statements if the dates' months correspond etc. But I am hoping there is some more automated method in python/matplotlib.
Upvotes: 0
Views: 1825
Reputation: 1075
You could use pandas for this:
import pandas as pd
import datetime
dates = [datetime.date(2015,01,05),
datetime.date(2015,01,18),
datetime.date(2015,01,25),
datetime.date(2015,02,18),
datetime.date(2015,03,07),
datetime.date(2015,03,27),]
df = pd.DataFrame({'dates':dates})
df.dates = pd.to_datetime(df.dates)
df.groupby(df.dates.dt.month).count().plot(kind='bar')
Gives:
The df.dates.dt.month
is getting the month for each. You could group by day, year, etc, in the same way.
Upvotes: 2