Display data points in boxplots

I am using the boxplot function to create boxplots of my data. But I would also like to plot my data on top of the boxplots.
Can anyone please help with that?
Below is an example of my code
Data1 = [0.2658 0.1969 0.3702 0.2259 0.2575 0.2253 0.4486 0.5385 0.3982 0.2899]';
Data2 = [0.2589 0.2094 0.3575 0.2391 0.2547 0.1987 0.4156 0.5443 0.394 0.3]';
Data3 = [0.2589 0.2094 0.3575 0.2391 0.2547 0.2087 0.4256 0.5243 0.3822 0.2983]';
group = [ ones(size(Data1));
2 * ones(size(Data2))
3 * ones(size(Data3))];
boxplot([Data1; Data2; Data3],group)
h = boxplot([Data1; Data2; Data3],group)
set(h,{'linew'},{2})
set(gca,'XTickLabel', {'Data1'; 'Data2'; 'Data3'})

 Accepted Answer

Adam Danz
Adam Danz on 2 May 2019
Edited: Adam Danz on 19 Sep 2019
After some slight rearrangement of your code, I added a secton that optionally scatters the x coordinates around the centers of the boxes. Set the 'spread' to 0 to plot data points in the center of the boxes.
allData = {Data1; Data2; Data3};
h = boxplot(cell2mat(allData),group); % old version: h = boxplot([allData{:}],group);
set(h, 'linewidth' ,2)
set(gca,'XTickLabel', {'Data1'; 'Data2'; 'Data3'})
hold on
xCenter = 1:numel(allData);
spread = 0.5; % 0=no spread; 0.5=random spread within box bounds (can be any value)
for i = 1:numel(allData)
plot(rand(size(allData{i}))*spread -(spread/2) + xCenter(i), allData{i}, 'mo','linewidth', 2)
end
The x-scatter is random so the the x coordinates will differ each time the plot is created unless the rng seed is controlled.

6 Comments

That's what I actually needed. Thanks a lot
Glad I could help. Not sure if you caught my update a minute ago but I made a slight change so that the scatter can be controlled.
Thanks for your solution, But is there a way to make this work without using data sets that have identical amounts of data points within them? Whenever I try to use this I get:
"Error using horzcat
Dimensions of arrays being concatenated are not consistent."
I recognise that my data sets arent all equal in both column and row so this is likely tripping it up, but is there a solution to this?
Sure; if the vectors stored in the cell array are vertical,
% Use this
h = boxplot(cell2mat(allData),group);
% instead of this
% h = boxplot([allData{:}],group);
DM
DM on 29 Jun 2020
Edited: DM on 29 Jun 2020
Is there a way to make each data appear in a different colour instead all of them being pink?
The plot() command only allows you to assign one color per object. So you could plot the values within a loop where you can assign a different color on each iteration. Another method would be to use the scatter() function that allows you to assign different color for each point.

Sign in to comment.

More Answers (0)

Asked:

on 2 May 2019

Commented:

on 29 Jun 2020

Community Treasure Hunt

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

Start Hunting!