mHelpMe
mHelpMe

Reputation: 6668

plotting bar chart make negative bars different colour to positive bars

I am plotting a bar chart in Matlab. I would like to know if it is possible to base the colours of the bars based on a simple condition? I would like all the positive bars to be say blue and the negative ones to be red. If this is possible can you please tell me how I can going about doing this in MATLAB?

Upvotes: 0

Views: 1365

Answers (2)

MeMyselfAndI
MeMyselfAndI

Reputation: 1320

Alternatively, you could include your conditions (here data>0 and data<0) as follows:

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

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

Upvotes: 2

am304
am304

Reputation: 13886

Yes, it's possible, see this solution on MATLAB Central.

Here's some example code extracted from this. The third column of the data is used to determine which colour to apply to each bar. In your case, you just need to check whether each value is positive or negative and change the colour accordingly.

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

Upvotes: 2

Related Questions