Home > Enterprise >  Plot in a different colors for y-values above x-axis
Plot in a different colors for y-values above x-axis

Time:04-27

Here I've plotted ((2*x.^2 3*exp(-x) -(100*a)).*sin(5*x))./(6*x.^2-9*x-42)-10 with input a=3, dx=0.1.

I would like to plot all positive y-values in blue and all negative y-values in red:

enter image description here

a = input('Please input a: ');
dx = input('Input step size dx: ');
if dx<0
   fprintf('dx must be a non-negative number.');
   while(dx<0)
       dx = input('Input step size dx: ');
   end
end
clf;
x = -10:dx:10;
y = ((2*x.^2 3*exp(-x) -(100*a)).*sin(5*x))./(6*x.^2-9*x-42)-10

plot(x,y)
ylim([-100,100])

To plot positive y-values in blue and negative y-values in red, I've tried initializing vectors for positive y-values and their domain, and the same vectors for negative y-values and their domain.

s = size(y);
x_1 = [];
x_2 = []; %negative
y_1 = [];
y_2 = []; %negative
for i = 1:s(2)
    if(y(i) >0)
        x_1 = [x_1,x(i)];
        y_1 = [y_1,y(i)];
    elseif (y(i) <0)
        x_2 = [x_2,x(i)];
        y_2 = [y_2,y(i)];
    end
end

s_x1 = size(x_1);
s_x1_lim = s_x1(2);
s_x2 = size(x_2);
s_x2_lim = s_x2(2);

plot(x_1,y_1,'b');
xlim([x_1(1), s_x1_lim]);
hold on
plot(x_2,y_2,'r');
xlim([x_2(1), s_x2_lim]);
hold on;
xlim([-10,10])
ylim([-100,100]);

Problem is, this approach leaves some overlap which I would prefer not to have. How can I change this?

enter image description here

CodePudding user response:

You can make two arrays: neg_x = x; neg_x (neg_x >0) = nan plot using 'r' and then the opposite for the positive values. This will, however, leave you with the pieces between the two arrays, i.e. your gaps. You can correct them by finding them and extending the index by one:

x = 0:0.1:6*pi;
y = sin(x);
neg_y = y; neg_y (neg_y>0) = nan;
tmp_y = isnan(neg_y);
idx = find(diff(tmp_y)==1);  % find gaps
neg_y(idx 1) = y(idx 1);  % correct gaps
idx = find(diff(tmp_y)==-1);
neg_y(idx) = y(idx);

pos_y = y; pos_y (pos_y<0) = nan;
plot(x, neg_y,'r');
hold on;
plot(x,pos_y,'b')

Using nan is a little help here, since MATLAB will automatically ignore those entries when plotting, i.e. leaving a nice gap, rather than a straight line.

Results in:

enter image description here

  • Related