How to add different colours to positive and negative regions of area plot?
12 次查看(过去 30 天)
显示 更早的评论
Hi, I am trying to make an area plot with separate colours for positive and negative regions. I tried separating the positive and the negative parts and then plotted both one upon another:
for i=1:length(mismatch)
if (mismatch(i) < 0)
neg_mismatch(i)=mismatch(i);
pos_mismatch(i)=0.0;
else
neg_mismatch(i)=0.0;
pos_mismatch(i)=mismatch(i);
end
end
The problem is there are overlap regions of positive and negative values around 0 values (see attachment) which makes the plot look ugly. I tried to interpolate values in between, but still no improvement!
x_neg=(1:length(neg_mismatch))';
y_neg=neg_mismatch;
xi_neg=(1:0.01:length(neg_mismatch))';
yi_neg = interp1(x_neg,y_neg,xi_neg,'cubic');
x_pos=(1:length(pos_mismatch))';
y_pos=pos_mismatch;
xi_pos=(1:0.01:length(pos_mismatch))';
yi_pos = interp1(x_pos,y_pos,xi_pos,'cubic');
figure;
hold on
h1=area(yi_neg);
h2=area(yi_pos);
hold off
Can anyone please help!
0 个评论
回答(1 个)
WAT
2015-9-22
The problem is that the area command is drawing lines from the actual data points to the zeroed out data, rather than connecting to the actual (but opposite signed) data point.
As a simple example, think of what would happen if you tried to do a positive/negative area plot for the simple two-point data set [-1,1].
There may be a more elegant solution, but one way is to insert a fake 0 data point wherever the data switch from positive to negative (or vice-versa):
%%MAKE UP SOME DATA
x = -10:.1:10;
y = sinc(x)+0.2*random('normal',0,1,1,length(x));
plot(y)
%%TRY SPLITTING IT THE OLD WAY
y1=y;y2=y;
y1(y1<0)=0; % zero out negative entries
y2(y2>0)=0; % zero out positive entries
figure
hold on
h1 = area(x,y1,'FaceColor','b')
h2 = area(x,y2,'FaceColor','r');
%%NOW INSERT ZEROS WHERE LINE CROSSES THE Y AXIS
% Insert 0s wherever data transitions from +/- or -/+
count = 0; % counter for number of fake 0's inserted
for ii=1:length(y)-1
i = ii+count; % i is the index in our new, possibly extended vectors
% find points with different signs
if(y(i+1)*y(i) < 0)
% find y intercept
x_fake = x(i) + abs(y(i))/(abs(y(i))+abs(y(i+1))) * (x(i+1)-x(i));
% put fake data into x and y arrays
x = [ x(1:i), x_fake , x(i+1:length(x))];
y = [ y(1:i), 0 , y(i+1:length(y))];
% increment counter
count = count+1;
end
end
% create y1 and y2, consisting of nonnegative and nonpositive entries
% of y respectively
y1=y; y2=y;
y1(y1<0) = 0;
y2(y2>0) = 0;
figure
hold on
area(x,y1,'FaceColor','b');
area(x,y2,'FaceColor','r');
hold off
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Title 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!