开发者

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 exam开发者_StackOverflowple, given:

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

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


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:

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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜