Plot histogram of epoch list, x axis by month-year in PyPlot

Kazh

With a list of epoch dates, is there a parameter in pyplot or numpy to have an histogram where the bins match the months in the data list? In this example, the list correspond to random date from 2012 to 2013. I would like that the histogram shows the bars from, for example, February 2012 to October 2013 if the values in data correspond only to dates from these months.

This code makes an histogram, but it separates manually for bins=24.

import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import random

data = [int(random.randint(1293836400, 1356994800)) for _ in range(1000)]

# convert the epoch format to matplotlib date format
mpl_data = mdates.epoch2num(data)

fig, ax = plt.subplots(1,1)
ax.hist(mpl_data, bins=24, ec='black')
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d.%m.%y'))
fig.autofmt_xdate()
plt.show()
Vince W.

In order to do this you have to pick out the timestamps at which the beginning of each month begins. Dates/Times are always a lot trickier than just regular numbers so while this code looks a bit cumbersome, it does work.

import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import random

data = [int(random.randint(1293836400, 1356994800)) for _ in range(1000)]

# create your bins as timestamps marked at the beginning of each month, using datetime objects to increment
import datetime as d
mindate = d.datetime.fromtimestamp(min(data))
maxdate = d.datetime.fromtimestamp(max(data))
bindate = d.datetime(year=mindate.year, month=mindate.month, day=1)
bins = [bindate.timestamp()]
while bindate < maxdate:
    if bindate.month == 12:
        bindate = d.datetime(year=bindate.year + 1, month=1, day=1)
    else:
        bindate = d.datetime(year=bindate.year, month=bindate.month + 1, day=1)
    bins.append(bindate.timestamp())
bins = mdates.epoch2num(bins)

mpl_data = mdates.epoch2num(data)
fig, ax = plt.subplots(1,1, figsize=(16, 4), facecolor='white')
ax.hist(mpl_data, bins=bins, ec='black')
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d.%m.%y'))
fig.autofmt_xdate()

enter image description here

Another approach is to use pandas to group data by month, and then counting them. The code is much shorter, and you can make a quick bar plot. To re-create your plot above would take more work, but this gives you a feel for things you can do with other tools:

srs = pd.DatetimeIndex(pd.Series(data) * 1e9)  # convert sec to nsec
df = pd.DataFrame({'count': np.ones(shape=len(srs))}, index=srs)
fig, ax = plt.subplots(1, 1, figsize=(16,4), facecolor='white')
df.groupby(pd.Grouper(freq='M')).count().plot.bar(ax=ax)

enter image description here

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Plot year below month on x axis

Plot pandas dataframe index formatted as Month-Year on x axis

How to create a grouped bar chart (by month and year) on the x-axis and values on the y-axis using matplotlib.pyplot?

time series plot with x axis ticks in month-year format in R

How can I sort x axis values (month-year) on ggplot2 bar plot correctly?

Switching month numbers to month names on x-axis of histogram matplotlib

Matplotlib Plot X-Axis by Month

Seaborn figure with multiple axis (year) and month on x-axis

Plot a list of tuples on x axis

Not able to group x-axis by month in a pyplot chart (Python)

Pyplot - Visualize histogram of a list

How to plot average in y axis for each x value in pyplot

matplotlib.pyplot plot x-axis ticks in equal range

Plot a histogram using the index as x-axis labels

R histogram plot controlling x-axis values

customize the value of x axis in histogram in python with pandas.plot

How to plot two level x-axis labels for a histogram?

Create a histogram showing month and year

Problem plotting data in Matlab (setting month and year in the x-axis)

Pandas: Adding multi level X axis to matplotlib/Seaborn (month and year)

SSRS : How to show all month of a year as X axis of a graph

MPAndroidChart: Dates on x-axis - sticky month and year

ggplot "day-month" x axis with facet wrap "year"

How to format date on x-axis to month and year in R

How to show x-axis with just month and year in line chart?

Histogram with string x axis

Bar plot with count on yaxis and year on x axis with 2 color groups

R ggplot bar plot with month on X-axis

Trying to add more space between labels in x-axis on pyplot histogram