How to make bar plot with group mean and add scatter plot on top to demonstrate samples within group?
Show older comments
I want to make something like this 

Accepted Answer
More Answers (1)
Muskan
on 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;
Categories
Find more on Scatter Plots in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!