MATLAB: How to obtain the handle of a histogram plot using the HIST function

figure handlehistMATLAB

I need to obtain the handle of a histogram plot which is obtained by using the HIST function. The HIST function does not return the handle when the following command is executed.
h = hist;
Instead, it returns the frequency values of the histogram bins and does not plot the histogram. This behavior is unlike any other graphics function in MATLAB.

Best Answer

It is not necessary to modify the HIST function in MATLAB to obtain the handle of the figure. You can use the GET and SET commands after plotting the histogram for the same as illustrated below.
To plot the histogram simply type 'hist(n)' or 'hist(x,y)' as your case may be. This will plot the histogram in a figure window.
To obtain the handle of the current figure you can use the GCF (Get Current Figure Handle) command as follows.
h = gcf;
This however will not return the handle to the histogram plot, but instead it will return the handle to the figure window. To return the handle to the actual bar diagram that HIST plots, you can use the 'children' property of the current axis of the figure. The reason for this is as follows.
A single figure can be associated with multiple axes on it. In our case, we are plotting only one histogram and thus have only one axes pair. The handle to this axes pair can be obtained using the GCA command. Since the bar diagram is plotted on this axes pair, it is a child object of this axes pair. The axes is the parent of the bar diagram. Thus using the GET command as follows,
h = get (gca, 'children');
we can obtain the handle for the actual bar diagram. Now to modify the properties of the bar diagram, you can use the SET command. For example, to change the color of the histogram you can use,
set (h, 'facecolor', [0.25 0.25 0.25]); % set a new RGB face color