Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Histogram in matplotlib, time on x-Axis

I am new to matplotlib (1.3.1-2) and I cannot find a decent place to start. I want to plot the distribution of points over time in a histogram with matplotlib.

Basically I want to plot the cumulative sum of the occurrence of a date.

date 2011-12-13 2011-12-13 2013-11-01 2013-11-01 2013-06-04 2013-06-04 2014-01-01 ... 

That would make

2011-12-13 -> 2 times 2013-11-01 -> 3 times 2013-06-04 -> 2 times 2014-01-01 -> once 

Since there will be many points over many years, I want to set the start date on my x-Axis and the end date, and then mark n-time steps(i.e. 1 year steps) and finally decide how many bins there will be.

How would I achieve that?

like image 396
Stophface Avatar asked Apr 16 '15 10:04

Stophface


People also ask

What is Figsize in histogram?

figsize : tuple (width, height) - The size of the output image. layout : tuple (rows, columns) - The layout in which the output graphs must be, for example, (4, 1) gives the figures in a single column and four rows. bins : int or sequence - Number of histogram bins to be used.

Can matplotlib plot real time graphs?

To create a real-time plot, we need to use the animation module in matplotlib. We set up the figure and axes in the usual way, but we draw directly to the axes, ax , when we want to create a new frame in the animation.


1 Answers

Matplotlib uses its own format for dates/times, but also provides simple functions to convert which are provided in the dates module. It also provides various Locators and Formatters that take care of placing the ticks on the axis and formatting the corresponding labels. This should get you started:

import random import matplotlib.pyplot as plt import matplotlib.dates as mdates  # generate some random data (approximately over 5 years) data = [float(random.randint(1271517521, 1429197513)) for _ in range(1000)]  # convert the epoch format to matplotlib date format  mpl_data = mdates.epoch2num(data)  # plot it fig, ax = plt.subplots(1,1) ax.hist(mpl_data, bins=50, color='lightblue') ax.xaxis.set_major_locator(mdates.YearLocator()) ax.xaxis.set_major_formatter(mdates.DateFormatter('%d.%m.%y')) plt.show() 

Result:

enter image description here

like image 99
hitzg Avatar answered Sep 26 '22 02:09

hitzg