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?
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).
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.
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.
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With