Boxplot and histogram in one plot
Mostrar comentarios más antiguos
Hey,
I think this question has been asked before:
But I could not find any proper solution;
so is there a way to achieve something like this:

I'm looking forward to hear your suggestions :)
1 comentario
Sambit Supriya Dash
el 6 de Mayo de 2021
Yes it is possible to get boxplot and histogram in one plot,
Example,
x = [1 2 3;4 5 6;7 8 9];
y = [5 4 3; 5 7 9; 1 9 3];
figure(1)
hist(x)
hold on
boxplot(y)
hold off
Hope, it helps.
Respuesta aceptada
Más respuestas (1)
Scott MacKenzie
el 6 de Mayo de 2021
Editada: Scott MacKenzie
el 7 de Mayo de 2021
This solution uses tiledlayout and boxchart, but you can adjust to use subplot and boxplot if you are running an older version of MATLAB:
n = 7;
y = randn(100,n);
tiledlayout(1, 2*n);
for i=1:n
nexttile;
boxchart(y(:,i));
set(gca,'visible', 'off', 'ylim', [-4 4]);
nexttile;
histogram(y(:,i), 20, 'orientation', 'horizontal');
set(gca,'visible', 'off', 'ylim', [-4 4]);
end
f = gcf;
f.Color = 'w';
f.Units = 'normalized';
f.Position = [.1 .2 .8 .4];

6 comentarios
Jakob Seifert
el 6 de Mayo de 2021
Scott MacKenzie
el 6 de Mayo de 2021
I just adjusted my answer so the histograms are horizontal. Is that what you are looking for?
Jakob Seifert
el 7 de Mayo de 2021
Scott MacKenzie
el 7 de Mayo de 2021
Editada: Scott MacKenzie
el 7 de Mayo de 2021
You're right. My solution creates 14 plots in 14 axes, all of which are made invisible. To get exacly what you want, you'd need to add all the plots to a single axis or add axes to the parent tiledlayout or figure. I don't know if that's possible.
One more step: it's important to set ylim so that the extent of the histograms align with the extent of the boxplots/outliers. For example, in the 5th pair of axes the boxplot does not show any outliers at the top but the histogram extends beyond the upper cap. This is because of a difference in y-limits between the neighboring axes.

Also, the ylim needs to match for all axes so that vertical differenced between columns of data are preserved.
For example, compare these two figures using the exact same data.
n = 7;
y = randn(100,n) .* [1:3:19];
figure()
boxchart(y)
figure()
tiledlayout(1, 2*n);
for i=1:n
nexttile;
boxchart(y(:,i));
set(gca,'visible', 'off');
nexttile;
histogram(y(:,i), 20, 'orientation', 'horizontal');
set(gca,'visible', 'off');
end
f = gcf;
f.Color = 'w';
f.Units = 'normalized';
f.Position = [.1 .2 .8 .4];
Scott MacKenzie
el 7 de Mayo de 2021
Hey, good point. Thanks. I just adjusted my solution to prevent this -- by setting the y-axis limits.
Categorías
Más información sobre Data Distribution Plots en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!



