MATLAB Answers

How to group values to display in bar charts while doing data analysis

5 views (last 30 days)
Tessa
Tessa on 30 Oct 2020
Commented: Peter Perkins on 18 Nov 2020 at 16:56
I am doing some data-analysis to see some weekly totals over time. Right now I am manually creating new tables to display everything in bar-charts, but I think that there has to be a better way. I load the data from excel, the data contains cells and doubles. The analysis I want to be doing contains only doubles. (I am using Matlab R2020b)
An example of what my data looks like:
Names = {'These';'are';'some';'random';'names';'yay'};
YearWeek = [201901;201901;201901;201902;201902;201902];
Duration = rand(6,1);
T = table(Names,YearWeek,Duration);
T =
6×3 table
Names YearWeek Duration
__________ _________ ________
{'These' } 2.019e+05 0.67874
{'are' } 2.019e+05 0.75774
{'some' } 2.019e+05 0.74313
{'random'} 2.019e+05 0.39223
{'names' } 2.019e+05 0.65548
{'yay' } 2.019e+05 0.17119
Now I want to make a bar chart in which I want to see the sum of the duration per YearWeek.
What I am doing right now is:
%Selecting the right data
selected_columns = [T.YearWeek,T.Duration];
%Sum duration per week
[year_week,~,location_year_week] = unique(selected_columns(:,1));
SumOfDurationPerWeek = zeros(height(year_week),2);
for i = 1:height(year_week)
SumOfDurationPerWeek(i,1) = year_week(i);
SumOfDurationPerWeek(i,2) = sum(selected_columns(location_year_week == i, 2));
end
%Plot as a bar chart
figure()
bar(SumOfDurationPerWeek(:,1),SumOfDurationPerWeek(:,2))
However I cannot believe that there is no easier way.
Shouldn't it be possible to create a bar chart immediately without summing all the values?

  0 Comments

Sign in to comment.

Accepted Answer

Ameer Hamza
Ameer Hamza on 30 Oct 2020
Even using splitapply() with findgroups() will be a simpler solution.

  6 Comments

Show 3 older comments
Peter Perkins
Peter Perkins on 18 Nov 2020 at 16:56
If you want weekly totals, a timetable and the retime function is the most straight-forward way. But your timestamps are numeric, so you'd need to convert things like 201901 into things like datetime(2018,12,31) or datetime(2019,1,6) (depending on how you define "week of year"), so it might be easier to leave them as numeric and use groupsummary.

Sign in to comment.

More Answers (0)

Products


Release

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by