绘制条形图使负条不同的颜色到正条

时间:2014-10-14 14:35:14

标签: matlab

我在Matlab中绘制条形图。我想知道是否可以根据简单条件确定条形的颜色?我希望所有正面的条形都说蓝色而负面的条形图则是红色的。如果有可能,请告诉我如何在MATLAB中进行此操作?

2 个答案:

答案 0 :(得分:2)

是的,可以,请参阅MATLAB Central上的this solution

这是从中提取的一些示例代码。数据的第三列用于确定要应用于每个条的颜色。在您的情况下,您只需要检查每个值是正还是负,并相应地更改颜色。

data = [.142 3 1;.156 5 1;.191 2 0;.251 4 0];
%First column is the sorted value
%Second column is the index for the YTickLabel
%Third column is the reaction direction
% Data(1,3) = 1 -> bar in red
% Data(1,3) = 0 -> bar in blue

% For each bar, check direction and change bar colour
H = data(:, 1);
N = numel(H);
for i=1:N
  h = bar(i, H(i));
  if i == 1, hold on, end
  if data(i, 3) == 1
    col = 'r';
  else
    col = 'b';
  end
  set(h, 'FaceColor', col) 
end

答案 1 :(得分:2)

或者,您可以按以下方式添加条件(此处为data>0data<0):

data = rand(8,1) - .5;

figure(1);
clf;
hold on;
bar(data.*(data>0), 'b');
bar(data.*(data<0), 'r');
相关问题