Conditionally Format Bar Chart
5 views (last 30 days)
Show older comments
Is it possible to create a conditionally formatted bar chart?
I have a time series bar chart that has positive and negative values, I would like to color code the bars based on a binary signal?
2 Comments
Answers (2)
Matt Tearle
on 5 Apr 2012
Not sure if I understand your comment exactly, but it sounds like you have x & y data, then another variable z(x) that is +1 or -1, and you want to color the (x,y) plot according to the value of z. If so:
% some fake data
x = 1:20;
y = randi(100,size(x))-50;
% signal of -1 or +1
z = randi([-1,1],size(x));;
% find the values where z = -1
idx = (z==-1);
% plot them
bar(x(idx),y(idx),'r')
hold on
% now the others (z = +1)
bar(x(~idx),y(~idx),'b')
set(gca,'XTickMode','auto')
hold off
The bar function messes with the axis ticks, hence the set command at the end. You could also specify the tick values manually:
set(gca,'XTick',x)
0 Comments
Thomas
on 5 Apr 2012
Don't know if there is an easier way, this is not too bad.. This gives lines like the example image..
clear all
close all
clc
c=(randn(10,1));
f=randi([-1 1],1,10);
f(f==0)=1;
f=f';
q=[f c] % this is your input with col 1 val -1 or 1, col 2 actual value
for i=1:length(q)
if q(i,1)==-1
line([i i],[0,q(i,2)],'Color','r')
hold on
else
line([i i],[0,q(i,2)],'Color','b')
hold on
end
end
line([0 length(q)],[0 0],'Color','k')
or try : this give bars
clear all
close all
clc
c=(randn(10,1));
f=randi([-1 1],1,10);
f(f==0)=1;
f=f';
q=[f c] % this is your input with col 1 val -1 or 1, col 2 actual value
val=(q(:,1)==1);
d=[1:length(q)];
bar(d(val),q(val,2),'r','LineWidth',1)
hold on
bar(d(~val),q(~val,2),'b','LineWidth',1)
0 Comments
See Also
Categories
Find more on Annotations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!