Andrew T
Andrew T

Reputation: 33

Colors in legend not matching the plot

I have to plot a few Maclaurin series and am having issues with the legend.

For these two equations-

x = (-1:.01:1);

% e^x
eqtn21 = 1; 
eqtn22 = 1 + x;
eqtn23 = 1 + x + x.^2/2;
eqtn24 = 1 + x + x.^2/2 + x.^3/6;
eqtn25 = exp(x);

% cos(x)
eqtn31 = 1;
eqtn32 = 1 - x.^2/2;
eqtn33 = 1 - x.^2/2 + x.^4/24;
eqtn34 = 1 - x.^2/2 + x.^4/24 - x.^6/720;
eqtn35 = cos(x);

subplot(2,2,1)
    plot(x,eqtn21,'r',x,eqtn22,'g',x,eqtn23,'b',x,eqtn24,'k',x,eqtn25,'c')
    legend('First Term','First Two Terms','First Three Terms','First Four Terms','Exact Function')

subplot(2,2,2)
    plot(x,eqtn31,'r',x,eqtn32,'g',x,eqtn33,'b',x,eqtn34,'k',x,eqtn35,'c')
    legend('First Term','First Two Terms','First Three Terms','First Four Terms','Exact Function')

When I plot them, the legend shows up but shows 5 red lines and doesn't match the colors on the plot.

Upvotes: 3

Views: 973

Answers (1)

bla
bla

Reputation: 26069

The issue is with eqtn21 and eqtn31. They are of size 1 while x is a vector of a different size. When you plot you need to match their sizes with the size of x if you want to have a constant line (so for all values of x you'll get 1), or eqtn21 = [1 1 1 1 ... 1];

An easy way to do it is to write eqtn21 = 1+0*x; etc. Other ways to do this can be do refine eqtn21 using repmat or matrix multiplication etc...

eqtn21=repmat(1,[1 numel(x)])

or

eqtn21=1*ones(1,numel(x))

etc...

Upvotes: 1

Related Questions