Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change the color of a specific bin in a histogram?

I wrote a code in MATLAB that plots a histogram. I need to color one of the bins in a different color than the other bins (let's say red). Does anybody know how to do it? For example, given:

A = randn(1,100);
hist(A);

How would I make the bin that 0.7 belongs to red?

like image 556
ariel Avatar asked Dec 17 '10 18:12

ariel


People also ask

Can histograms have different colors?

A histogram can be N-dimensional. Although harder to display, a three-dimensional color histogram for the above example could be thought of as four separate Red-Blue histograms, where each of the four histograms contains the Red-Blue values for a bin of green (0-63, 64-127, 128-191, and 192-255).

How do you add color to a histogram in R studio?

If you want to change the colors of the default histogram, you merely add the arguments border or col . You can adjust, as the names itself kind of give away, the borders or the colors of your histogram.

How do you change the color of a Histplot?

We can manually change the histogram color using the color argument inside distplot() function. In this example, we have used the argument color=”purple” to make purple histogram as shown below.


2 Answers

An alternative to making two overlapping bar plots like Jonas suggests is to make one call to bar to plot the bins as a set of patch objects, then modify the 'FaceVertexCData' property to recolor the patch faces:

A = randn(1,100);                 %# The sample data
[N,binCenters] = hist(A);         %# Bin the data
hBar = bar(binCenters,N,'hist');  %# Plot the histogram
index = abs(binCenters-0.7) < diff(binCenters(1:2))/2;  %# Find the index of the
                                                        %#   bin containing 0.7
colors = [index(:) ...               %# Create a matrix of RGB colors to make
          zeros(numel(index),1) ...  %#   the indexed bin red and the other bins
          0.5.*(~index(:))];         %#   dark blue
set(hBar,'FaceVertexCData',colors);  %# Re-color the bins

And here's the output:

alt text

like image 88
gnovice Avatar answered Nov 15 '22 07:11

gnovice


I guess the easiest way is to draw the histogram first and then just draw the red bin over it.

A = randn(1,100);
[n,xout] = hist(A); %# create location, height of bars
figure,bar(xout,n,1); %# draw histogram

dx = xout(2)-xout(1); %# find bin width
idx = abs(xout-0.7) < dx/2; %# find the bin containing 0.7
hold on;bar([xout(idx)-dx,xout(idx),xout(idx)+dx],[0,n(idx),0],1,'r'); %# plot red bar
like image 22
Jonas Avatar answered Nov 15 '22 05:11

Jonas