Boxplot and histogram in one plot (2024)

69 views (last 30 days)

Show older comments

Jakob Seifert on 6 May 2021

  • Link

    Direct link to this question

    https://support.mathworks.com/matlabcentral/answers/822795-boxplot-and-histogram-in-one-plot

  • Link

    Direct link to this question

    https://support.mathworks.com/matlabcentral/answers/822795-boxplot-and-histogram-in-one-plot

Commented: RJ on 31 Jul 2021

Accepted Answer: Adam Danz

Hey,

I think this question has been asked before:

How to overlay box plot with distribution histogram in the same graph - MATLAB Answers - MATLAB Central (mathworks.com)

But I could not find any proper solution;

so is there a way to achieve something like this:

Boxplot and histogram in one plot (2)

I'm looking forward to hear your suggestions :)

1 Comment

Show -1 older commentsHide -1 older comments

Sambit Supriya Dash on 6 May 2021

Direct link to this comment

https://support.mathworks.com/matlabcentral/answers/822795-boxplot-and-histogram-in-one-plot#comment_1504155

  • Link

    Direct link to this comment

    https://support.mathworks.com/matlabcentral/answers/822795-boxplot-and-histogram-in-one-plot#comment_1504155

Open in MATLAB Online

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.

Sign in to comment.

Sign in to answer this question.

Accepted Answer

Adam Danz on 7 May 2021

  • Link

    Direct link to this answer

    https://support.mathworks.com/matlabcentral/answers/822795-boxplot-and-histogram-in-one-plot#answer_694390

  • Link

    Direct link to this answer

    https://support.mathworks.com/matlabcentral/answers/822795-boxplot-and-histogram-in-one-plot#answer_694390

Edited: Adam Danz on 7 May 2021

Open in MATLAB Online

This method uses patch objects to display histograms next to each boxplot. It's based on another answer that displays probability density distributions next to vertical scatter plots.

You only need to replace the x and y data and can copy-paste the rest of the code.

Inputs.

x : 1xn vector defining the x coordinate of n boxplots.

y : mxn matrix of raw data for n boxplots

rng('default') % for reproducibility

x = 0:5:30;

y = (randn(300, numel(x)) + linspace(.5,5,numel(x))) .* linspace(.5,2,numel(x));

Set spacing

binWidth = 0.4; % histogram bin widths

hgapGrp = .05; % horizontal gap between pairs of boxplot/histograms (normalized)

hgap = 0.2; % horizontal gap between boxplot and hist (normalized)

Compute histogram counts & edges

hcounts is an nx2 cell array containing the {counts, edges} for each distribution.

maxCount is the maximum bin count across all distributionts, used to normalize patch heights

hcounts = cell(size(y,2),2);

for i = 1:size(y,2)

[hcounts{i,1}, hcounts{i,2}] = histcounts(y(:,i),'BinWidth',binWidth);

end

maxCount = max([hcounts{:,1}]);

Plot boxplots

fig = figure();

ax = axes(fig);

hold(ax,'on')

xInterval = mean(diff(sort(x))); % x-interval (best if x is at a fixed interval)

normwidth = (1-hgapGrp-hgap)/2;

boxplotWidth = xInterval*normwidth;

boxplot(ax,y,'Positions',x,'Widths',boxplotWidth,'OutlierSize',3,'Labels',compose('%d',x))

Add vertical histograms (patches)

histX0 = x + boxplotWidth/2 + hgap; % histogram base

maxHeight = xInterval*normwidth; % max histogram height

for i = 1:size(y,2)

% Normalize heights

height = hcounts{i,1}/maxCount*maxHeight;

% Compute x and y coordinates

xm = [zeros(1,numel(height)); repelem(height,2,1); zeros(2,numel(height))] + histX0(i);

yidx = [0 0 1 1 0]' + (1:numel(height));

ym = hcounts{i,2}(yidx);

% Plot patches

patchHandles(i) = patch(xm(:),ym(:),[0 .75 1],'FaceAlpha',.4);

end

xlim([-2.5, 32.5])

Boxplot and histogram in one plot (5)

Method 2 with color control

With just a few changes to the code above, you can use boxplotGroup() from the file exchange to set up colors of boxplots and histogram similar to the example in your question.

%% Inputs

rng('default') % for reproducibility

x = 0:5:30;

y = (randn(300, numel(x)) + linspace(.5,5,numel(x))) .* linspace(.5,2,numel(x));

%% Set Spacing

binWidth = 0.4; % histogram bin widths

hgapGrp = .15; % horizontal gap between pairs of boxplot/histograms (normalized)

hgap = 0.06; % horizontal gap between boxplot and hist (normalized)

%% Compute histogram counts & edges

hcounts = cell(size(y,2),2);

for i = 1:size(y,2)

[hcounts{i,1}, hcounts{i,2}] = histcounts(y(:,i),'BinWidth',binWidth);

end

maxCount = max([hcounts{:,1}]);

%% Plot boxplotsGroup()

fig = figure();

ax = axes(fig);

hold(ax,'on')

% Convert y (mxn matrix) to 1xn cell array of mx1 vectors, required by boxplotWidths

yc = mat2cell(y,size(y,1),ones(1,size(y,2)));

xInterval = 1; %x-interval is always 1 with boxplot groups

normwidth = (1-hgapGrp-hgap)/2;

boxplotWidth = xInterval*normwidth;

% Define colors for each boxplot

colors = lines(size(y,2));

% Plot colored boxplots

bph = boxplotGroup(ax,yc,'Widths',boxplotWidth,'OutlierSize',3,'PrimaryLabels',compose('%d',x),'Colors',colors);

set(findobj(bph.boxplotGroup,'-property','LineWidth'), 'LineWidth', 1) % increase line widths

%% Add vertical histograms (patches) with matching colors

xCoordinate = 1:size(y,2); %x-positions is always 1:n with boxplot groups

histX0 = xCoordinate + boxplotWidth/2 + hgap; % histogram base

maxHeight = xInterval*normwidth; % max histogram height

patchHandles = gobjects(1,size(y,2));

for i = 1:size(y,2)

% Normalize heights

height = hcounts{i,1}/maxCount*maxHeight;

% Compute x and y coordinates

xm = [zeros(1,numel(height)); repelem(height,2,1); zeros(2,numel(height))] + histX0(i);

yidx = [0 0 1 1 0]' + (1:numel(height));

ym = hcounts{i,2}(yidx);

% Plot patches

patchHandles(i) = patch(xm(:),ym(:),colors(i,:),'EdgeColor',colors(i,:),'LineWidth',1,'FaceAlpha',.45);

end

Boxplot and histogram in one plot (6)

5 Comments

Show 3 older commentsHide 3 older comments

Jakob Seifert on 7 May 2021

Direct link to this comment

https://support.mathworks.com/matlabcentral/answers/822795-boxplot-and-histogram-in-one-plot#comment_1507195

  • Link

    Direct link to this comment

    https://support.mathworks.com/matlabcentral/answers/822795-boxplot-and-histogram-in-one-plot#comment_1507195

This is insane, thank you very much.

Adam Danz on 7 May 2021

Direct link to this comment

https://support.mathworks.com/matlabcentral/answers/822795-boxplot-and-histogram-in-one-plot#comment_1507550

  • Link

    Direct link to this comment

    https://support.mathworks.com/matlabcentral/answers/822795-boxplot-and-histogram-in-one-plot#comment_1507550

Later I realized my boxplotGroup() function could be used to control the color so I added a 2nd version to my answer. The same could be achieved using boxchart but I haven't worked out those details.

RJ on 31 Jul 2021

Direct link to this comment

https://support.mathworks.com/matlabcentral/answers/822795-boxplot-and-histogram-in-one-plot#comment_1665962

  • Link

    Direct link to this comment

    https://support.mathworks.com/matlabcentral/answers/822795-boxplot-and-histogram-in-one-plot#comment_1665962

This seems great and exactly what I was looking for too.

I wondered if there is a way to do this with boxplot y vectors of different lengths or am I missing something? And to add x labels? Thanks!!

Adam Danz on 31 Jul 2021

Direct link to this comment

https://support.mathworks.com/matlabcentral/answers/822795-boxplot-and-histogram-in-one-plot#comment_1666032

  • Link

    Direct link to this comment

    https://support.mathworks.com/matlabcentral/answers/822795-boxplot-and-histogram-in-one-plot#comment_1666032

An easy workaround when using vectors of unequal length is to pad the shorter vectors with NaN values so all vecs are the same length and then you can combine them into a matrix. padarray may be helpful.

For labels, use text() function or labelpoints().

RJ on 31 Jul 2021

Direct link to this comment

https://support.mathworks.com/matlabcentral/answers/822795-boxplot-and-histogram-in-one-plot#comment_1666077

  • Link

    Direct link to this comment

    https://support.mathworks.com/matlabcentral/answers/822795-boxplot-and-histogram-in-one-plot#comment_1666077

Awesome thanks, I got it working with padcat.

Sign in to comment.

More Answers (1)

Scott MacKenzie on 6 May 2021

  • Link

    Direct link to this answer

    https://support.mathworks.com/matlabcentral/answers/822795-boxplot-and-histogram-in-one-plot#answer_693325

  • Link

    Direct link to this answer

    https://support.mathworks.com/matlabcentral/answers/822795-boxplot-and-histogram-in-one-plot#answer_693325

Edited: Scott MacKenzie on 7 May 2021

Open in MATLAB Online

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];

Boxplot and histogram in one plot (13)

6 Comments

Show 4 older commentsHide 4 older comments

Jakob Seifert on 6 May 2021

Direct link to this comment

https://support.mathworks.com/matlabcentral/answers/822795-boxplot-and-histogram-in-one-plot#comment_1504620

  • Link

    Direct link to this comment

    https://support.mathworks.com/matlabcentral/answers/822795-boxplot-and-histogram-in-one-plot#comment_1504620

Thank you for your answer, but this isn't what I am exactly looking for.

I want the y-axis to be the possible outputs for the boxplot, as well as the histogram. That is, I want the histogram to be rotated by 90° degrees. (look at the picture embedded in my original post)

Scott MacKenzie on 6 May 2021

Direct link to this comment

https://support.mathworks.com/matlabcentral/answers/822795-boxplot-and-histogram-in-one-plot#comment_1504650

  • Link

    Direct link to this comment

    https://support.mathworks.com/matlabcentral/answers/822795-boxplot-and-histogram-in-one-plot#comment_1504650

I just adjusted my answer so the histograms are horizontal. Is that what you are looking for?

Jakob Seifert on 7 May 2021

Direct link to this comment

https://support.mathworks.com/matlabcentral/answers/822795-boxplot-and-histogram-in-one-plot#comment_1506775

  • Link

    Direct link to this comment

    https://support.mathworks.com/matlabcentral/answers/822795-boxplot-and-histogram-in-one-plot#comment_1506775

Yes this looks much better! But as I understand it, you turned off the individual axes. I need two "overall" axes; meaning something like this:

https://www.mathworks.com/help/examples/stats/win64/CreateBoxPlotsForGroupedDataExample_01.png

But this soultions is already pretty good ! thank you

Scott MacKenzie on 7 May 2021

Direct link to this comment

https://support.mathworks.com/matlabcentral/answers/822795-boxplot-and-histogram-in-one-plot#comment_1506940

  • Link

    Direct link to this comment

    https://support.mathworks.com/matlabcentral/answers/822795-boxplot-and-histogram-in-one-plot#comment_1506940

Edited: Scott MacKenzie on 7 May 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.

Adam Danz on 7 May 2021

Direct link to this comment

https://support.mathworks.com/matlabcentral/answers/822795-boxplot-and-histogram-in-one-plot#comment_1507160

  • Link

    Direct link to this comment

    https://support.mathworks.com/matlabcentral/answers/822795-boxplot-and-histogram-in-one-plot#comment_1507160

Edited: Adam Danz on 7 May 2021

Open in MATLAB Online

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.

Boxplot and histogram in one plot (19)

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)

Boxplot and histogram in one plot (20)

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];

Boxplot and histogram in one plot (21)

Scott MacKenzie on 7 May 2021

Direct link to this comment

https://support.mathworks.com/matlabcentral/answers/822795-boxplot-and-histogram-in-one-plot#comment_1507230

  • Link

    Direct link to this comment

    https://support.mathworks.com/matlabcentral/answers/822795-boxplot-and-histogram-in-one-plot#comment_1507230

Hey, good point. Thanks. I just adjusted my solution to prevent this -- by setting the y-axis limits.

Sign in to comment.

Sign in to answer this question.

See Also

Categories

MATLABGraphicsFormatting and Annotation

Find more on Formatting and Annotation in Help Center and File Exchange

Tags

  • boxplot
  • histogram
  • statistics
  • marginal

Products

  • MATLAB

Release

R2021a

Community Treasure Hunt

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

Start Hunting!

An Error Occurred

Unable to complete the action because of changes made to the page. Reload the page to see its updated state.


Boxplot and histogram in one plot (23)

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a web site from the following list

Americas

  • América Latina (Español)
  • Canada (English)
  • United States (English)

Europe

  • Belgium (English)
  • Denmark (English)
  • Deutschland (Deutsch)
  • España (Español)
  • Finland (English)
  • France (Français)
  • Ireland (English)
  • Italia (Italiano)
  • Luxembourg (English)
  • Netherlands (English)
  • Norway (English)
  • Österreich (Deutsch)
  • Portugal (English)
  • Sweden (English)
  • Switzerland
    • Deutsch
    • English
    • Français
  • United Kingdom(English)

Asia Pacific

  • Australia (English)
  • India (English)
  • New Zealand (English)
  • 中国
  • 日本Japanese (日本語)
  • 한국Korean (한국어)

Contact your local office

Boxplot and histogram in one plot (2024)

FAQs

What is a combination histogram and box plot? ›

Adding a boxplot on top of a histogram can help you in better understanding the distribution of the data and visualizing outliers as well as quartiles positions.

What do boxplots show that histograms don t choose the best answer? ›

What are box plots? Histograms are great for showing what data ranges are most and least common, but they do not tell details like the range or the median. You can use box plots to present these values.

When should you choose a Boxplot over a histogram? ›

Histograms are particularly useful in determining the underlying probability distribution of a dataset, while box plots are more useful when comparing between multiple datasets. They are less detailed than histograms and take up less space.

What can you see in the histogram that you cannot see in the boxplot? ›

The box plot helps you see skewness, because the line for the median will not be near the center of the box if the data is skewed. The box plot helps identify the 25th and 75th percentiles better than the histogram, while the histogram helps you see the overall shape of your data better than the box plot.

How both the Boxplot and the histogram can indicate a skewed distribution? ›

The boxplot indicates a skewed distribution when there are outliers to only one side. The histogram indicates a skewed distribution when there are very small or very large observations on only one side of the​ distribution, far from the center. frequency of observations in a certain range.

What is a combination plot? ›

Combination charts are designed to visually highlight differences between sets of data and make it easy to see one set of information presented in relationship with other data. For instance, in the example below, the combination chart uses a bar chart and a line graph together.

What is the combination of box plot and density plot? ›

A violin plot is a hybrid of a box plot and a kernel density plot, which shows peaks in the data. It is used to visualize the distribution of numerical data. Unlike a box plot that can only show summary statistics, violin plots depict summary statistics and the density of each variable.

What is a double box plot? ›

A double box plot is two box and whisker plots on the same number line. They are used for comparisons of two different populations on the same subject. We can pull a lot of information out of a double box plot.

What is a disadvantage of using a Boxplot rather than a histogram? ›

Final answer: A boxplot does not provide information about the frequency or specific distribution shape of data values, unlike a histogram, which shows the frequency or relative frequency and reveals the distribution's shape, such as whether it is skewed or has multiple modes.

What are the disadvantages of using a histogram instead of a dot plot? ›

So, What's Wrong With the Histogram?
  • It depends (too much) on the number of bins. ...
  • It depends (too much) on variable's maximum and minimum. ...
  • It doesn't allow to detect relevant values. ...
  • It doesn't allow to discern continuous from discrete variables. ...
  • It makes it hard to compare distributions.
Jan 24, 2021

What can you not tell from a box plot? ›

On the downside, a box plot's simplicity also sets limitations on the density of data that it can show. With a box plot, we miss out on the ability to observe the detailed shape of distribution, such as if there are oddities in a distribution's modality (number of 'humps' or peaks) and skew.

How to match a box plot to a histogram? ›

Match the box plots and histograms together.

To identify matching data start by identifying tails (left or right) and symmetric type data. We can see, that A and 3 have right tails, and thus are both right skewed. So they are a match. C and 2 have left tails, and thus are both left skewed and so are a match.

What is the main advantage of Boxplots over histograms? ›

The main advantage of boxplots over stemplots and histograms is Boxplots make it easy to compare several distributions, as in this example. B) Here's the best way to solve it.

What is one reason one might choose a histogram over a boxplot? ›

D) A histogram can be used to approximate the range. What is not visible in a box plot are the data values. The box plot only shows the outlier, the 1 1 1st and 3 3 3rd quartiles, and the median.

How do you match a histogram? ›

To make the histograms match, we can interpolate the values from the source image (SkySat) into the range of the target image (Landsat), using a piecewise-linear function that puts the correct ratio of pixels into each bin.

How are box plots similar to histograms? ›

Just like histograms, box plots should only be used with continuous or discrete variables. Box plots are similar to histograms in that they both display the distribution of a variable, but box plots make it to more straightforward to identify the actual value of the minimum, Q1, median (Q2), Q3, and maximum.

Is it always possible to construct a corresponding box plot given a histogram? ›

Given a dot plot, it is always possible to construct a corresponding box plot. Given a histogram, it is always possible to construct a corresponding box plot.

References

Top Articles
SkillsUSA Selects Welding Competitor for WorldSkills 2024
What Is Savory: All About The Herb and 4 Tasty Recipes - Recipes.net
Euro Jackpot Uitslagen 2024
Hotels Near Okun Fieldhouse Shawnee Ks
5 Fastest Ways To Become Rich by Investing in the Stock Market
Parc Soleil Drowning
Inmate Inquiry Mendocino
T-Mobile SW 56th Street & SW 137th Ave | Miami, FL
Craigslist Cars For Sale San Francisco
Schuylkill County Firewire
The 10 Best Drury Hotels in the United States
Lojë Shah me kompjuterin në internet. Luaj falas
Terraria Melee Build Progression Guide & Best Class Loadouts
Paperless Pay.talx/Nestle
2006 Lebanon War | Summary, Casualties, & Israel
Cubilabras
Myworld Interactive American History Pdf
Https //Myapps.microsoft.com Portal
Naval Academy Baseball Roster
Unmhealth My Mysecurebill
Haktuts.in Coin Master 50 Spin Link
Mychart Login Wake Forest
Xdm16Bt Manual
ONE PAN BROCCOLI CASHEW CHICKEN
Language levels - Dutch B1 / 2 –What do these language levels mean? - Learn Dutch Online
Ts Central Nj
Bellagio Underground Tour Lobby
Any Ups Stores Open Today
Www Muslima Com
France 2 Journal Télévisé 20H
Www.playgd.mobi Wallet
Rachel Pizzolato Age, Height, Wiki, Net Worth, Measurement
New York Sports Club Carmel Hamlet Photos
Tandon School of Engineering | NYU Bulletins
Wells Fargo Careers Log In
Claudy Jongstra on LinkedIn: Tonight at 7 PM opens NAP+, a new, refreshing and enriching addition to…
8 Common Things That are 7 Centimeters Long | Measuringly
Scotlynd Ryan Birth Chart
Metrocast Channel Lineup
Breakroom Bw
600 Aviator Court Vandalia Oh 45377
Stock Hill Restaurant Week Menu
Accident On 40 East Today
Gasbuddy Sam's Club Madison Heights
Corn And Tater Fest 2023
304-733-7788
Amanda Balionis Renner Talks Favorite Masters Interviews, the Evolution of Golf Twitter, and Netflix’s ‘Full Swing’
Wayfair Outlet Dayton Ohio
FINAL FANTASY XI Online 20th Anniversary | Square Enix Blog
Martin's Point Otc Catalog 2022
Dragon Ball Super Super Hero 123Movies
Latest Posts
Article information

Author: Golda Nolan II

Last Updated:

Views: 6810

Rating: 4.8 / 5 (78 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Golda Nolan II

Birthday: 1998-05-14

Address: Suite 369 9754 Roberts Pines, West Benitaburgh, NM 69180-7958

Phone: +522993866487

Job: Sales Executive

Hobby: Worldbuilding, Shopping, Quilting, Cooking, Homebrewing, Leather crafting, Pet

Introduction: My name is Golda Nolan II, I am a thoughtful, clever, cute, jolly, brave, powerful, splendid person who loves writing and wants to share my knowledge and understanding with you.