Boxplot and histogram in one plot
显示 更早的评论
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 个评论
Sambit Supriya Dash
2021-5-6
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.
采纳的回答
更多回答(1 个)
Scott MacKenzie
2021-5-6
编辑:Scott MacKenzie
2021-5-7
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 个评论
Jakob Seifert
2021-5-6
Scott MacKenzie
2021-5-6
I just adjusted my answer so the histograms are horizontal. Is that what you are looking for?
Jakob Seifert
2021-5-7
Scott MacKenzie
2021-5-7
编辑:Scott MacKenzie
2021-5-7
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
2021-5-7
Hey, good point. Thanks. I just adjusted my solution to prevent this -- by setting the y-axis limits.
类别
在 帮助中心 和 File Exchange 中查找有关 Data Distribution Plots 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!



