Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I plot a histogram of months with dates in matplotlib

Tags:

So here is my problem, that I need to solve with matplotlib. I have found variants of this online already but I have a new wrinkle that I cannot seem to figure out based on those.

I have a list of dates in this format

  1. 20160522
  2. 20160527
  3. 20160626
  4. 20160725...

and I need to make a histogram of the relative frequencies of their months. I would like this histogram to have the actual month labels on there so that the x-axis has labels like "Jan", "Feb", etc...

How do I do this with the matplotlib dates routines? It seems as though they don't play nicely with histograms in this manner where I am only looking at the monthly distribution and not the days or years....

like image 663
Steven Ehlert Avatar asked Apr 07 '17 17:04

Steven Ehlert


1 Answers

An easy solution might be the following:
You don't need to use datetime objects at all, but just convert the list of datestrings into a list of month numbers, e.g. "20150419" maps to 4. This list can then be easily plotted as a histogram. In order to get the months' names, you may simply write them down or obtain them from a list of datetime objects.

import numpy as np
import matplotlib.pyplot as plt
import datetime

dates = ["20150204", "20150404","20151004","20151005", "20151007","20150704",
         "20160404", "20160522","20160527","20160626", "20160725","20170223"]
dtm = lambda x: int(x[4:6])
months = list(map(dtm, dates))

fig, ax = plt.subplots()
bins = np.arange(1,14)
ax.hist(months, bins = bins, edgecolor="k", align='left')
ax.set_xticks(bins[:-1])
ax.set_xticklabels([datetime.date(1900,i,1).strftime('%b') for i in bins[:-1]] )

plt.show()

enter image description here

like image 133
ImportanceOfBeingErnest Avatar answered Sep 24 '22 10:09

ImportanceOfBeingErnest