version 1.13.0.0 (81.7 KB) by
Jonathan C. Lansey

Compares multiple sets of data elegantly. Set bins and axis bounds to be appropriate for the data.

**Editor's Note:** This file was selected as MATLAB Central Pick of the Week

Summary of what function does:

1) Automatically sets the number and range of the bins to be appropriate for the data.

2) Compares multiple sets of data elegantly on one or more plots, with legend or titles. It also graphs the mean and standard deviations. It can also plot the median and mode.

3) Outputs text with the useful statistics for each distribution.

4) Allows for changing many more parameters

Highlighted features (see below for details)

'boxplot' adds boxplots to the graphs

'separate' to plot each set on its own axis, but with the same bounds

'binfactor' change the number of bins used, larger value =more bins

'samebins' force all bins to be the same for all plots

'legend' add a legend in the graph (default for structs)

'noerror' remove the mean and std plot from the graph

'median' add the median of the data to the graph

'text' return many details about each graph even if not plotted

Syntax:

t = nhist(Y) bins the elements of Y into equally spaced containers

and returns a string with information about the distributions.

If Y is a cell array or a structure nhist will make graph the

binned (discrete) probability density function of each data

set for comparison on the same graph. It will return A cell

array or structure which includes a string for each set of

data.

[t, N, X]= nhist(...) also returns the number of items in each bin, N,

and the locations of the left edges of each bin. If Y is a

cell array or structure then the output is in the same form.

nhist(Y,'PropertyName', . . . )

nhist(Y,'PropertyName',PropertyValue, . . . )

% Examples

Cell array example:

A={randn(1,10^5),randn(10^3,1)+1};

nhist(A,'legend',{'u=0','u=1'});

nhist(A,'legend',{'u=0','u=1'},'separate');

Structure example:

A.zero=randn(1,10^5); A.one=randn(10^3,1)+1;

nhist(A);

nhist(A,'color','summer')

nhist(A,'color',[.3 .8 .3],'separate','median','noerror')

nhist(A,'binfactor',4)

nhist(A,'samebins')

nhist(A,'median','noerror')

Jonathan C. Lansey (2020). Plot and compare histograms; pretty by default (https://www.mathworks.com/matlabcentral/fileexchange/27388-plot-and-compare-histograms-pretty-by-default), MATLAB Central File Exchange. Retrieved .

Created with
R2009a

Compatible with any release

**Inspired:**
TACTICS Toolbox, Efficient 2D histogram, no toolboxes needed

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

Start Hunting!Create scripts with code, output, and formatted text in a single executable document.

Chaminda BandaraThank you!

Amine BohiPornpong sakdapatMichael HelmbergerAPHoomanXiaoPeyman Obeidynice job, thanks. Is there a way to center the bin at a specific range. I want to use two subplots sitting on top of each other and want the center of bins at the same centers.

Peyman Obeidynice job, thanks. Is there a way to center the bin at a specific range. I want to use two subplots sitting on top of each other and want the centre of bins at a same centers.

Erik ReinertsenJonathan C. LanseyIlyas, the default produces a pdf, sometimes the pdf value is>1 but that doesn't mean something is wrong since the integral is still=1.

For colors, choose: 'color','colormap' and set your color map to be whatever you like.

The linestyles cannot be changed.

IlyasOK. So I just figured out that we have to use 'proportion' to get probability.

I have smooth histogram:

I want to draw dashed lines.

I want to change color each of the line.

How can I do that? Seems impossible.

IlyasI believe the pdf showing on the y axis is wrong.

I also compared with matlab, but they give quite different values on the y axis.

Jaziel SotoHello there, thanks for this code, It's great. I have a question, Is there any way to plot de histogram from de lowest value to the highest value in the x axis? Thanks in advance

AbdulghaniJonathan C. Lansey@Dan, the histograms are normalized by default to have an area of 1. You can change it to have the values 'sum' to 1 instead by choosing the parameter 'proportion' (though you aren't the first to ask me this so I'm considering changing how that parameter works)

DanHi - This is a great tool. I can't seem to be able to have it simply produce a normalized histogram. I've tried nhist(testdata,'normal'), nhist(testdata,'normalhist'), nhist(testdata,'separate'), but they all seem to produce a graph that is identical to just nhist(testdata). Please advise.

Jonathan C. LanseyThanks for the nice comments!

@Kelly, I'll see about making the changes, thanks for the suggestion!

AbbazabaThanks! You saved me a ton of work.

Kelly KearneyI want to love this function; its basic function is great, and it has helped me analyze datasets many times. Two things would make it better...

1) Return graphics handles! It drives me crazy that I always have to handle-dive via findobj to modify properties and analyze details after plotting.

2) Set default line width, axis font size, font name, etc. to match the user's defaults. You may prefer the bigger font size and thicker lines, but not everyone does, and it's a bit of a hassle to pass these properties with every call to nhist just to maintain no change.

Sam NazariExtremely useful. I use nhist on a daily basis. Thanks.

Luba PesisGreat code! Very helpful. Thank you so much for sharing!

Luba PesisHamedCarlos RochinhaAlready found a solution!

Again... Thanks for your built!

Carlos RochinhaIs it possible add a Kernel line to histogram?

I don't know how to do it.

Great script by the way!

HamedThanks for clarifying that Jonathan!

nicolasThanks a lot for that function. Amazing built in customisation functionalities.

Nicolas K.

Jonathan C. Lansey@Hamed, Thanks for the detailed comment.

nhist default chooses 11 bins rather than 10 bins for your data. The last nhist bin goes from 0.99868 to 1.021 which includes a single data point (0.9987) which happens to be on the far left of that bin.

To show your data better you might try choosing much smaller bins.

nhist(a,'f',10);

or manually set the maximum x limit to 1

nhist(a,'maxx',1);

hope this helps!

@Sarvesh, I've been meaning to implement log10 axis scaling but I haven't yet, would be super-useful. Thanks for the suggestion.

HamedI was using the function to compare the histogram of various data that I have and I noticed a bug in the function:

assume I have the following vector:

a= [NaN

0.775638811223563

0.973350006434936

0.943383964815490

0.962485362625822

0.948715322933571

0.962665074880784

0.966254225826858

0.934862260833738

0.939722782566127

0.976272235874088

0.959721480543415

0.970921202148258

0.976427283935447

0.936619607135822

0.892363443960771

0.967451691235654

0.986163657939425

0.947595390619081

0.980476539443364

0.975284102968746

0.900963987843455

0.925688573062275

0.936566882483817

0.962093098847172

0.926006354448264

0.909062533065121

0.936198208983877

0.932202530466075

0.894278361270968

0.967018528033492

0.913017842148726

0.958207171237400

0.843404538130596

0.929806874900785

0.927507509937351

0.900191997038867

0.822578263381990

0.998683319306805

0.897414661468888

0.965044081678391

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

0.951962073112260

0.933648805276507

0.806753966859453

0.883217399140238

0.933100903484828

0.922399197241776

0.914314867418531

0.963654633644814

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

NaN

];

Try using nhist and hist and you will see that they won't match. This vector contains numbers below 1 however when plotting histogram using nhist it will give a bin for values grater than 1 which is not correct.

Am I missing something?

SarveshIs there a way to change the xaxis into log10 or other scales before plotting? It seems that the bins are chosen in linear scale and I was wondering if there is a way to define the bins before hand?

thanks!

Rvery helpfull function..

RJonathan C. LanseyI just updated the function to have much nicer colors (thanks to colorbrewer). You can choose your own colors by changing the colormap and choosing the setting: 'color','colormap'

PatrickVery helpful function!

It would be nice in the future to have the option to provide custom colors as an argument for 'color'. For instance, if plotting data d={setA,setB}, I'd like to be able to specify line colors besides the standard colormaps for setA and setB. So for example:

nhist(d,... 'color',{[1 0 0],[0 1 1]});

Or equivalently:

nhist(d,... 'color',{'r','c'}).

DavidDavidJonathan C. Lansey@Duane, yes it does its best with all kinds of data. I just changed the title of the file to hopefully be more clear.

Duane HanselmanYou say "Plot and compare nice histograms by default." Does this function also work for histograms that are not nice?

Raz ShimoniI am using this function is my app. Very usful. Thank you.

Andrey KanLeoVery useful plotting function.

I do have a suggestion though: add an option to do the 'separate' plots option in a 2d grid, instead of having only a single column of plots.

Jonathan C. Lansey@Shinobue111, a PDF may be >1 as long as the area = 1, as we discussed.

wwI love this function. However, I'm getting PDF values of >1 when I compare several distributions on one figure... that shouldn't really be possible :/

Jiaqivery flexible by using the provided parameters. useful to draw concise but informative histgrams. Thanks for the nice work.

Jonathan C. LanseyThanks for the suggestion - I went ahead and implemented robust handling of NaN and inf data points.

Amanda WhitmireI really like this function, but I wish it could handle NaNs in my data. Thanks for sharing your code.

Mark BrandonVery nice bit of code and very useful. Thanks for posting it.

Laurent SWell documented and many features, great job!

Guido LagosGreat script, Jonathan, just what I was looking for! Best regards

AhmedSimon RobinsonGreat. Works cleanly and comprehensively. It also runs where, for me, hist crashes (http://www.mathworks.de/matlabcentral/newsreader/view_thread/240876).

Rob CampbellFor many data sets it may be more useful to have a standard histogram and overlay a smooth fit. You should at least provide an option for creating a smooth fit.

Please don't rate your own files: you, of course, think your work is amazing. That's why you've put it up here for all to see.