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

3 次查看(过去 30 天)
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?

采纳的回答

Ameer Hamza
Ameer Hamza 2020-10-30
Even using splitapply() with findgroups() will be a simpler solution.
  6 个评论
Peter Perkins
Peter Perkins 2020-11-18
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Bar Plots 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by