transform bar chart with separate bars (for each value of y) to bar chart with overlapping bars
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Alberto Acri
am 20 Aug. 2023
Kommentiert: Alberto Acri
am 21 Aug. 2023
Hi. I need to transform this figure:
load matrix.mat
matrix = matrix(5:7,:);
figure();
cm = [1,0,0; 0,0,1; 0,1,0; 1,0,0.52];
hbh = barh(matrix(:,1), matrix(:,[2 3 4 5]));
for k = 1:numel(hbh)
hbh(k).FaceColor = cm(k,:);
hbh(k).EdgeColor = [0,0,0];
end
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1460677/image.png)
into this one:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1460682/image.png)
I tried the following way but I don't get the same result.
figure
hbh = barh(matrix(:,1), matrix(:,[2 3 4 5]),'stacked');
cm = [[1,0,0]; [0,0,1]; [0,1,0]; [1,0,0.52]];
for k = 1:numel(hbh)
hbh(k).FaceColor = cm(k,:);
hbh(k).EdgeColor = [0,0,0];
end
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1460687/image.png)
6 Kommentare
Rik
am 21 Aug. 2023
The reason I included the max call was for robustness. If at one point a negative diff occurs, I would like to prevent unexpected behavior.
the cyclist
am 21 Aug. 2023
I understand. But after the sort, a negative diff can't occur. (But if I am wrong about the sorting, then the max would be required, as you state.)
Akzeptierte Antwort
the cyclist
am 20 Aug. 2023
load matrix
M = matrix(:,2:end);
[sortedM,sortingIndex] = sort(M,2);
cm = [[1,0,0]; [0,0,1]; [0,1,0]; [1,0,0.52]];
figure
hold on
for mi = 1:height(sortedM)
hbh = barh(matrix(mi,1), [sortedM(mi,1),diff(sortedM(mi,:),1,2)],'stacked');
for k = 1:width(sortedM)
hbh(k).FaceColor = cm(sortingIndex(mi,k),:);
end
end
2 Kommentare
the cyclist
am 20 Aug. 2023
I stuck to answering what you asked for, but be aware that this method of plotting bars "in front of each other" can be somewhat deceptive, from an information point of view. For example, the green bar at 68 is nearly the same value as the blue bar, but the visual impact is tiny. (I think that's the reason @Dyuman Joshi thought you didn't want it at all.)
It would take more work, but you might want to consider using the method of overlaying bars that is described on this documentation page.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Discrete Data Plots finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!