How to plot stacked bar over stacked bar ?

Hello All
I have data set with size 12x4x76. 12 Represents 12 months, 4 represents 4 sub groups in each month and 76 represent 76 years. I want to plot x-axis as years and y-axis as Months as bar chart. So for a single bar it will be divided into 12 equal divisions representing the months and each division will be divided into 4 parts, height of each part will be decided by the values. So the it will be like stcked bar over a stacked bar. How to do that, any help will be highly appreciated. Image is attached for the sample plot.

 Accepted Answer

Maybe something like this:
load Data
tmp = plot_data./sum(plot_data,2);
tmp = reshape(flip(permute(tmp,[2 1 3]),1),[],size(tmp,3));
bar(tmp.','stacked')
N = 12;
yt = linspace(0,N,2*N+1);
ytl = strings(1,2*N+1);
ytl(2:2:end) = string(datetime(0,1:N,1,'Format','MMM'));
set(gca(), ...
'YLim',[0 N], ...
'YTick',yt, ...
'YTickLabels',ytl, ...
'TickDir','out')

4 Comments

You could add the following to group by color.
nGroups = 4;
% Trim the axes colororder to the first n colors
% This assumes there are at least n colors, otherwise
% define the colororder instead of trimming existing colors.
ax = gca;
ax.ColorOrder(nGroups+1:end, :) = [];
% Set the axes colormap to match the colororder and add a colorbar
ax.Colormap = ax.ColorOrder;
cb = colorbar(ax);
% label the color bar
ax.CLim = [0 1];
cbarTicks = linspace(ax.CLim(1), ax.CLim(2), nGroups*2+1);
cbarTicks(1:2:end) = [];
cb.Ticks = cbarTicks;
cb.TickLabels = compose('G%d',1:nGroups);
load Data
tmp = plot_data./sum(plot_data,2);
tmp = reshape(flip(permute(tmp,[2 1 3]),1),[],size(tmp,3));
bar(tmp.','stacked')
N = 12;
yt = linspace(0,N,2*N+1);
ytl = strings(1,2*N+1);
ytl(2:2:end) = string(datetime(0,1:N,1,'Format','MMM'));
set(gca(), ...
'YLim',[0 N], ...
'YTick',yt, ...
'YTickLabels',ytl, ...
'TickDir','out')
nGroups = size(plot_data,2);
% Trim the axes colororder to the first n colors
% This assumes there are at least n colors, otherwise
% define the colororder instead of trimming existing colors.
ax = gca;
ax.ColorOrder(nGroups+1:end, :) = [];
% Set the axes colormap to match the colororder and add a colorbar
ax.Colormap = ax.ColorOrder;
cb = colorbar(ax);
% label the color bar
ax.CLim = [0 1];
cbarTicks = linspace(ax.CLim(1), ax.CLim(2), nGroups*2+1);
cbarTicks(1:2:end) = [];
cb.Ticks = cbarTicks;
cb.TickLabels = compose('G%d',1:nGroups);
You're welcome!

Sign in to comment.

More Answers (0)

Categories

Tags

Asked:

on 11 Mar 2025

Commented:

on 12 Mar 2025

Community Treasure Hunt

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

Start Hunting!