How to create stacked histogram with arrays of different length

14 visualizaciones (últimos 30 días)
Gian Violi
Gian Violi el 6 de Mzo. de 2019
Editada: ch_tsai el 17 de Oct. de 2023
Basically I have column arrays with multiple observations, each belonging to a different category but every element has a different lenght. I want to be able to do something like this, whit each color representing a array (or category).4aBSy.png
I tried to concatenate the arrays into a bigger array and then stacking bars but didn't help beacuse of the lenght issue.
  2 comentarios
Martin Roth
Martin Roth el 1 de Oct. de 2021
Editada: Martin Roth el 1 de Oct. de 2021
Better late than never. Check if this solution fits for your problem:
% Create dummy data
A=-20+40*rand(500,1);
B=randn(400,1)*20;
Total=[A;B];
Steps=[0,numel(A),numel(B)];
[N,edges,bins] = histcounts(Total);
% Plot stacked histogram
figure;
colors=lines;
hold on
for i=1:length(Steps)-1
histogram(Total(1+Steps(i):end),'BinEdges',edges,'FaceColor',colors(i,:));
hold on
end
ch_tsai
ch_tsai el 17 de Oct. de 2023
Editada: ch_tsai el 17 de Oct. de 2023
I was trying to find a similar function and found this answer. Your code looks good, thank you! I would like to make it more generalized. For example, if there are more than two set of data, in the last part of your for loop, it's better to write in this way.
% Copy from your code--
% Create dummy data
A=-20+40*rand(500,1);
B=randn(400,1)*20;
C=-25+40*rand(500,1);
D=randn(400,1)*10;
Total=[A;B;C;D];
Steps=[0,numel(A),numel(B),numel(C),numel(D)];
[N,edges,bins] = histcounts(Total);
% Plot stacked histogram
figure;
colors=lines;
hold on
for i=1:length(Steps)-1
histogram(Total(1+sum(Steps(1:i)):end),'BinEdges',edges,'FaceColor',colors(i,:));%sum of Steps(1:i) was added
hold on
end

Iniciar sesión para comentar.

Respuestas (0)

Categorías

Más información sobre Histograms en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by