如何更改直方图中特定bin的颜色?

时间:2010-12-17 18:45:22

标签: matlab plot histogram

我在MATLAB中编写了一个绘制直方图的代码。我需要将其中一个箱子的颜色与其他箱子颜色不同(让我们说是红色)。有谁知道怎么做?例如,给定:

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

我如何制作0.7属于红色的bin?

2 个答案:

答案 0 :(得分:6)

制作两个重叠的条形图(例如Jonas suggests)的另一种方法是拨打bar一个电话,将这些二元组绘制为一组patch objects,然后修改'FaceVertexCData' property重新着色补丁面:

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

这是输出:

alt text

答案 1 :(得分:2)

我想最简单的方法是首先绘制直方图,然后在上面绘制红色框。

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