recipes : Plotting : Distributions : Modifying histogram properties

Problem

How do I modify the properties of a histogram?

Solution

A histogram is a patch object, so we will obtain the handle to the patch object and modify it. The tricky part is that the hist command doesn't return the handles of the plotted object, as does the plot command.

hist(randn(1,100)) %Plot a histogram

%Find the handle of the histogram
H=findobj('type','patch');

%Make the bars pink
set(H,'facecolor',[1,0.7,0.7],'edgecolor',[0.5,0,0])

Discussion

With many other graphics functions, such as plot, calling them with an output argument will return a handle to the the plot object. e.g. H=plot([0,1],[0,1],'-r') plots a red diagonal line and returns the handle for this line as the variable H. You can then modify the line using the set command. Calling hist with an output argument does something different, however: it returns the bin heights of the histogram but plots nothing. With two output arguments it returns both the bin heights and the x axis locations of the bins. e.g. [heights,xLocations]=hist(randn(1,100)). You can then use the bar command to plot these data: H=bar(xLocations,heights) The output of bar, H, is the handle of the plotted bars.