Take the 2-minute tour ×

I'm trying to plot the frequencies of different colour pixels in an image. I can draw three separate histograms on three separate figures, but I'd like to draw them all on the same figure, with red for red, green for green etc. From what I can tell from answers on this and other sites, the following should work, but it doesn't, only the second appears. What am I doing wrong?

hold on;

x = 0:1:255;
figure ('name', 'red') ;
red = (newImg(:,:,1));
r = red(:)';
r = cast(r,'double');
[graph1,graph2] = hist (r,x);
bar(graph2,graph1, 'FaceColor', 'r','EdgeColor','r')

green = (newImg(:,:,2));
g = green(:)';
g = cast(g,'double');
[graph1,graph2] = hist (g,x);
bar(graph2,graph1, 'FaceColor', 'b','EdgeColor','b')

hold off;
share|improve this question
add comment

3 Answers

You can plot all histograms (RGB channels) in a simpler way, for example:

colormap([1 0 0 ; 0 1 0; 0 0 1]); %RGB

Here I reshape newImg to be a Nx3 matrix, equivalent to the [r; g ;b] that you created. Then a single hist can process them, and using a custom color map, draws each channel with the correct color it represents.

share|improve this answer
add comment

You need to create a new figure (and/or axes) before calling hold on, since the hold-state applies on a per-axes basis, and the command hold on applies to the current axes. Modify the NextPlot property of axes if you want to control the hold state more precisely.

Also, to plot multiple histograms, distributionPlot from the File Exchange can be useful; in your case, example #7.

share|improve this answer
add comment

Fixed, the 'hold on' needs to come after the first graph is drawn; I assumed it was a toggle - you switch 'hold on' and it keeps holding til you turn it off, apparently not...

share|improve this answer
add comment

Your Answer


