How to make bar plot with group mean and add scatter plot on top to demonstrate samples within group?
37 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Marietta
am 22 Jul. 2024
Kommentiert: Star Strider
am 22 Jul. 2024
I want to make something like this
0 Kommentare
Akzeptierte Antwort
Star Strider
am 22 Jul. 2024
Bearbeitet: Star Strider
am 22 Jul. 2024
Apparently the group means are the heights of the bars.
Try this —
MC1 = randn(50,2)*10 + [80 81]; % Motion Class 1 Data
MC2 = randn(50,2)*10 + [78 82]; % Motion Class 2 Data
GM1 = mean(MC1);
GM2 = mean(MC2);
figure
hb = bar([GM1;GM2]);
hb(1).BarWidth = 1;
yline(33, '--k')
Ax = gca;
Ax.XTickLabel = [];
Ax.YTick = [0 33 50 100];
hold on
hb(1).DisplayName = 'Motion Class 1';
fa1 = 0.25;
hb(1).FaceAlpha = fa1;
xd1 = hb(1).XEndPoints;
fc1 = hb(1).FaceColor;
hs1 = scatter(xd1, MC1, 25, fc1, 'filled', 'DisplayName','Class 1 Data');
for k = 1:numel(hs1)
hs1(k).MarkerFaceAlpha = fa1;
end
hb(2).DisplayName = 'Motion Class 2';
fa2 = 0.25;
hb(2).FaceAlpha = fa1;
xd2 = hb(2).XEndPoints;
fc2 = hb(2).FaceColor;
hs2 = scatter(xd2, MC2, 25, fc2, 'filled', 'DisplayName','Class 2 Data');
for k = 1:numel(hs2)
hs2(k).MarkerFaceAlpha = fa2;
end
hold off
legend([hb hs1(1) hs2(1)], 'Location','north')
Position the legend wherever you want it. It may be necessary tto set xlim to be wider on thte right to fit it in the 'east' location.
EDIT — Corrected typographical errors.
.
2 Kommentare
Weitere Antworten (1)
Muskan
am 22 Jul. 2024
Hi,
As per my understanding, to create a bar plot with group means and overlay a scatter plot to show individual samples within each group in MATLAB, you can follow these steps:
- Calculate Group Means: Compute the mean for each group.
- Create the Bar Plot: Plot the group means using the "bar" function.
- Overlay the Scatter Plot: Use the "scatter" function to plot individual samples on top of the bar plot.
Here is an example code on how you can achieve the same:
% Sample data
group1 = randn(10, 1) + 5;
group2 = randn(10, 1) + 7;
group3 = randn(10, 1) + 6;
% Combine data into a cell array
data = {group1, group2, group3};
% Calculate group means
means = cellfun(@mean, data);
% Create the bar plot
figure;
hold on;
bar(means, 'FaceColor', [0.7 0.7 0.7], 'EdgeColor', 'k');
% Overlay scatter plot of individual samples
for i = 1:length(data)
scatter(repmat(i, length(data{i}), 1), data{i}, 'filled', 'jitter', 'on', 'jitterAmount', 0.15);
end
% Customize plot
xlabel('Group');
ylabel('Value');
title('Bar Plot with Group Means and Individual Samples');
set(gca, 'XTick', 1:length(data), 'XTickLabel', {'Group 1', 'Group 2', 'Group 3'});
hold off;
Siehe auch
Kategorien
Mehr zu Scatter Plots finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!