# How to create bar graph with portions (multi-dimensional)?

4 views (last 30 days)
Martti Ilvesmäki on 20 Jul 2021
Answered: Martti Ilvesmäki on 21 Jul 2021
I want to create a bar graph with following qualities:
• Bar itself is split into 3 color categories, indicating portions between variables (individual y-axis from 0 - 100 %)
• Overall bar height indicates another variable height (individual y-axis)
So in total the data has 3 dimensions and it combines pie chart qualities to bar graph. This would be very nice way to visualize the data as I'm conducting near infrared spectroscopy analysis and want to compare thickness values in addition to absorption.
I think I need combine multiple y-axis with stacked groupping style (as in the picture below).
How to create this kind of bar graph?

the cyclist on 20 Jul 2021
This example from the documentation shows exactly how to do it.
y = [2 2 3;
2 5 6;
2 8 9;
2 11 12];
bar(y,'stacked')
You may need to adjust the code a bit, because it seems like you want to use proportions rather than values.
Martti Ilvesmäki on 21 Jul 2021
This is good but missing the second y-axis (one for intensity, one for portions). I found now a way to do it by utilizing bar and plot graph and will post it as answer. Based on documentation too: https://www.mathworks.com/help/matlab/creating_plots/overlay-line-plot-on-bar-graph-using-different-y-axes-1.html

Martti Ilvesmäki on 21 Jul 2021
Although the bar height itself doesn't indicate value of 2nd y-axis, the plot serves well at least for my purpose.
x = categorical({'sample 1' 'sample 2' 'sample 3' 'sample 4'});
x = reordercats(x, {'sample 1' 'sample 2' 'sample 3' 'sample 4'});
y = zeros(3,4) + 1/3;
y2 = [100 200 300 250];
yyaxis left
b= bar(x,y, 'stacked');
b(1).FaceColor = [0.9290 0.6940 0.1250]; %Yellow
b(2).FaceColor = [0 0.4470 0.7410]; %Blue
b(3).FaceColor = [0.8500 0.3250 0.0980]; %Orange
yyaxis right
p = plot(x, y2, 'LineWidth', 5, 'Color', 'g');
End result:

R2021a

### Community Treasure Hunt

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

Start Hunting!