MATLAB中直方图的条件着色

时间:2014-08-09 14:57:47

标签: matlab graph histogram matlab-guide

我有一个直方图,我想要使用此规则进行条件着色:

高于50的值red条和低于50的值都有blue条。

假设我们有这个输入矩阵:

X = [32 64 32 12 56 76 65 44 89 87 78 56 96 90 86 95 100 65];

我想要MATLAB的默认bin并在X轴(bin)上应用这种着色。我正在使用GUIDE设计我的GUI,这个直方图是我GUI中的一个轴。

enter image description here

这是我们的常规图表。高于50的条形应为红色,低于50的条形应为绿色(X轴)。高于50的条形应为红色和?

3 个答案:

答案 0 :(得分:1)

我认为这可以做你想要的(根据评论)。 50左右的酒吧分为两种颜色。这是通过使用补丁来更改该栏的一部分颜色来完成的。

%// Data:
X = [32 64 32 12 56 76 65 44 89 87 78 56 96 90 86 95 100 65]; %// data values
D = 50; %// where to divide into two colors

%// Histogram plot:
[y n] = hist(X); %// y: values; n: bin centers
ind = n>50; %// bin centers: greater or smaller than D?
bar(n(ind), y(ind), 1, 'r'); %// for greater: use red
hold on %// keep graph, Or use hold(your_axis_handle, 'on')
bar(n(~ind), y(~ind), 1, 'b'); %// for smaller: use blue
[~, nd] = min(abs(n-D)); %// locate bar around D: it needs the two colors
patch([(n(nd-1)+n(nd))/2 D D (n(nd-1)+n(nd))/2], [0 0 y(nd) y(nd)], 'b');
%// take care of that bar with a suitable patch

enter image description here

答案 1 :(得分:0)

首先排序X:

X = [32 64 32 12 56 76 65 44 89 87 78 56 96 90 86 95 100 65]; 
sorted_X = sort(X)

sorted_X:

sorted_X =

第1至14栏

12    32    32    44    56    56    64    65    65    76    78    86    87    89

第15至18栏

90    95    96   100

然后基于50分割数据:

idx1 = find(sorted_X<=50,1,'last');
A = sorted_X(1:idx1);
B = sorted_X(idx1+1:end);

将其显示为两个不同的直方图。

hist(A);
hold on;
hist(B); 
h = findobj(gca,’Type’,’patch’);
display(h) 
set(h(1),’FaceColor’,’g’,’EdgeColor’,’k’);
set(h(2),’FaceColor’,’r’,’EdgeColor’,’k’);

答案 2 :(得分:0)

X = [32 64 32 12 56 76 65 44 89 87 78 56 96 90 86 95 100 65];

然后你创建一个直方图,但你只会用它来获取二进制数,元素数和位置数:

[N,XX]=hist(X);
close all

最后这里是你使用元素数量(N)和前一个hist的位置(XX)并为它们着色的代码

figure;
hold on;
width=8;
for i=1:length(N)
    h = bar(XX(i), N(i),8);
    if  XX(i)>50
        col = 'r';
    else
        col = 'b';
    end
    set(h, 'FaceColor', col)
end

在这里你可以考虑使用多个if if然后你可以设置多种颜色

欢呼声