How can I plot categories and sub-categories in a bar graph?
3 views (last 30 days)
Show older comments
Hello!
I was wondering how to plot different categories and sub-categories in a bar plot. I did represent one of the categories (Category_1). Now, I would like to plot the second category ("Category 2") in exactly the same way, but leaving some space between both categories, with exactly the same subcategories (120,150,175 and so on).
I would also like to know if there is a way to place the category name in the x-axis and the sub-category name at the top of each bar column.
This is the code I have implemented to get the graph:
categories = categorical({'120','150','175','200','250'});
cat1_120 = [5 6 7 8 9];
cat1_150 = [4 5 7 8 9];
cat1_175 = [3 2 4 5 6];
cat1_200 = [1 2 2 3 4];
cat1_250 = [1 2 1 2 3];
Category_1 = [cat1_120; cat1_150; cat1_175; cat1_200; cat1_250];
bar(categories,Category_1,1,'stacked')
Thanks in advance!!

0 Comments
Answers (1)
Samayochita
on 6 Feb 2025
Hi Inés Encabo,
You can achieve this using MATLAB's “tiledlayout”(https://www.mathworks.com/help/matlab/ref/tiledlayout.html) for plotting both the categories side by side, ensuring space between them. Also, you can customize the x-axis labels and place sub-category names at the top of each bar using “text” function. You can remove the x-axis labels (120, 150, etc.) by setting “xticklabels({})”.
The below code implements exactly this:
% Define categories and subcategories
categories = categorical({'120°C', '150°C', '175°C', '200°C', '250°C'});
cat1_120 = [5 6 7 8 9];
cat1_150 = [4 5 7 8 9];
cat1_175 = [3 2 4 5 6];
cat1_200 = [1 2 2 3 4];
cat1_250 = [1 2 1 2 3];
% Data for Category 1
Category_1 = [cat1_120; cat1_150; cat1_175; cat1_200; cat1_250];
% Data for Category 2 (modify values to distinguish)
Category_2 = Category_1 + 2;
% Create tiled layout for side-by-side plots
t = tiledlayout(1,2, 'TileSpacing', 'compact', 'Padding', 'compact');
% Plot Category 1
nexttile;
b1 = bar(categories, Category_1, 1, 'stacked');
ylabel('SIC - Specific Investment Cost (S/kW)');
xlabel('Category 1');
xticklabels({}); % Remove x-axis labels
% Add labels on top of bars
for i = 1:length(categories)
y_pos = sum(Category_1(i,:)); % Top of stacked bar
text(categories(i), y_pos + 1, string(categories(i)), ...
'HorizontalAlignment', 'center');
end
% Plot Category 2
nexttile;
b2 = bar(categories, Category_2, 1, 'stacked');
ylabel('SIC - Specific Investment Cost (S/kW)');
xlabel('Category 2');
xticklabels({}); % Remove x-axis labels
% Add labels on top of bars
for i = 1:length(categories)
y_pos = sum(Category_2(i,:));
text(categories(i), y_pos + 1, string(categories(i)), ...
'HorizontalAlignment', 'center');
end
Hope this helps!
0 Comments
See Also
Categories
Find more on 2-D and 3-D Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!