hossein.kh
hossein.kh

Reputation: 15

Coloring a plot partially in Matlab

I am going to plot a parameter called force in terms of frequency. my plot is going to be a semilogy plot ( I mean in "Y" direction it should be logarithmic) but as I know force is negative in some frequencies so in logarithmic plot it can not be drawn. All in all, the think I want is that I want to draw the force semilogarithmic and have the negative parts also in graph in a different color. semilogy(frequency,abs(force(2800,:))) I don't know how to change the colors of negative parts. Thank you

Upvotes: 0

Views: 70

Answers (2)

codeaviator
codeaviator

Reputation: 2565

This answer is basically the same as this other answer but with a little more detail.

Take the following sample dataset:

freq = linspace(0, 2*pi);
force = 1e6*sinc(freq);

force is a vector that contains positive and negative values, therefore, if we use semilogy with this data we will get a logarithmic plot of the positive values only (as you mentioned):

>> semilogy(freq, force, 'b*');
Warning: Negative data ignored

semilogy positive values only

If you want to plot the absolute value of the negative values, you can use logical indexing to find the indices of the negative values like this:

idx = force < 0;

And then plot these values in red color on the same axes:

hold on;
semilogy(freq(idx), abs(force(idx)), 'r*');

semilogy positive and negative values

You can also use this syntax to produce the same result:

semilogy(freq, force, 'b*', freq(idx), abs(force(idx)), 'r*');

Upvotes: 2

am304
am304

Reputation: 13886

I would use logical indexing:

freq = 0:1000; % frequency vector
force = 10*rand(size(freq))-5; % some random data between -5 and +5
semilogy(freq(force>0),force(force>0),'b-',freq(force<0),abs(force(force<0)),'r-')

which gives the following plot:

enter image description here

Upvotes: 1

Related Questions