0
votes

I have an array of values in the datetime format. Each value represent an event happening at the specified date and time. How can I plot event frequency in events per day, events per month, etc?

I already managed to plot events per hour of the day using histogram(mydata.Hour)

Thank you for your answers!

EDIT: some precisions after the first answer below:

yes, that's what I'm doing already using histogram and data.Hour. However, what I want to do is compute the average number of event per day, and plotting that all along the time period my events are.

here is a working example:

% generating 500 random events
dates = datetime(now-1000*rand(500,1),'convertfrom','datenum');

figure;
edges = -0.5:23.5;
histogram(dates.Hour,edges)
title('Events per hours of the day')
xlim ([-0.5 23.5])
ax1 = gca;
ax1.XTick = 0:2:23;
ax1.XTickLabel = {'Midnight','2','4','6','8','10','Noon','14','16','18','20','22'};
ax1.XTickLabelRotation = 45;

figure;
daynumber = weekday(dates);
histogram(daynumber)
title('Events per days of the week')
ax2 = gca;
ax2.XTick = [1:7];
ax2.XTickLabel = {'Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'};
ax2.XTickLabelRotation = 45;
1

1 Answers

0
votes

Assuming you have an array of datetimes already, you can access the day, hour, minute, second, etc. of each datetime object with:

datetime.Day
datetime.Hour
datetime.Minute

Using this notation, we can use a simple array to keep count of how many events happen at each day/hour/minute/etc. and then use a bar graph to plot the results. Two examples are shown below and you can extrapolate from these to modify for what you need.

Here's how it would work for plotting the event frequency for every hour in one day:

hours_count = zeros(24,1);
for dt = 1:length(datetimes)
    hour = datetimes(dt).Hour;
    hours_count(hour+1) = hours_count(hour+1) + 1;
end

bar(hours_count)
set(gca,'Xtick',1:24,'XTickLabel',strtrim(cellstr(num2str([0:23]'))))
xlabel('Hour of the Day')
ylabel('Number of Events')

Here's how it would work for plotting the event frequency for every day in one month:

days_in_the_month = 30;
days_count = zeros(days_in_the_month,1);
for dt = 1:length(datetimes)
    day = datetimes(dt).Day;
    days_count(day) = days_count(day) + 1;
end

bar(days_count)
set(gca,'Xtick',1:days_in_the_month,'XTickLabel',strtrim(cellstr(num2str([1:days_in_the_month]'))))
xlabel('Day of the Month')
ylabel('Number of Events')