2010-12-17 78 views
5

我在MATLAB中編寫了一個繪製直方圖的代碼。我需要用不同顏色的箱子給其中一個箱子着色(比方說紅色)。有人知道該怎麼做嗎?例如,給定:如何更改直方圖中特定倉的顏色?

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

我該如何製作0.7屬於紅色的bin?

回答

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 
+0

謝謝,但我在尋找一種方式ŧ o繪製直方圖.. – ariel 2010-12-17 19:27:14

+1

@ariel:看起來我在調用'bar'時犯了一個錯誤。現在它應該工作。 – Jonas 2010-12-17 19:56:07

+0

+1並確認它有效。 – gnovice 2010-12-17 20:16:47

6

到使兩個重疊條曲線等Jonas suggests另一種方法是使一個呼叫到bar繪製箱爲一組patch objects,然後修改重新着色補丁面孔:

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

+0

當我看到直方圖只是一個單獨的對象後,我甚至沒有檢查過酒吧系列給你個別的句柄。 +1更謹慎。 – Jonas 2010-12-18 03:59:11