Effacer les filtres
Effacer les filtres

How to make bar plot with group mean and add scatter plot on top to demonstrate samples within group?

33 vues (au cours des 30 derniers jours)
I want to make something like this

Réponse acceptée

Star Strider
Star Strider il y a environ 11 heures
Modifié(e) : Star Strider il y a environ 11 heures
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.
.

Plus de réponses (1)

Muskan
Muskan il y a environ 12 heures
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:
  1. Calculate Group Means: Compute the mean for each group.
  2. Create the Bar Plot: Plot the group means using the "bar" function.
  3. 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;

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by