Having trouble with legend
3 views (last 30 days)
Show older comments
Here is my code:
%Line Colors
strColor = {'-r','-g','-b'};
%Legend String
strLegend = {'nSamples = 5','nSamples = 10','nSamples = 15'};
for k = 1:length(n)
%sample values
newX = linspace(xpts(1),xpts(end),n(k));
subplot(1,3,k);
hold on
%Creating coefficients with polyfit
p = interp1(xpts,ypts,newX,'spline');
%Plotting x and y values as blue dots
plot(xpts,ypts,'ko','MarkerFaceColor','k','MarkerSize',4);
hold on
%Lines
plot(newX,p,strColor{k});
hold on
%legend('Data',strLegend(k));
subplot(1,3,k);
legend('Data',strLegend(k));
%Labeling graph
title('Plotting with polyfit and polyval');
end
I am attempting to plot 'Data' for the black dots and the strLegend for the colored line on the legend. Right now it is only plotting the strLegend in legend, and it is saying they are the black dots.
0 Comments
Answers (2)
Peng Li
on 11 May 2020
Edited: Peng Li
on 11 May 2020
Try this
%Line Colors
strColor = {'-r','-g','-b'};
%Legend String
strLegend = {'nSamples = 5','nSamples = 10','nSamples = 15'};
for k = 1:length(n)
%sample values
newX = linspace(xpts(1),xpts(end),n(k));
subplot(1,3,k);
hold on
%Creating coefficients with polyfit
p = interp1(xpts,ypts,newX,'spline');
%Plotting x and y values as blue dots
p2 = plot(xpts,ypts,'ko','MarkerFaceColor','k','MarkerSize',4);
hold on
%Lines
p3 = plot(newX,p,strColor{k});
hold on
%legend('Data',strLegend(k));
% subplot(1,3,k);
% legend('Data',strLegend(k));
legend([p p2 p3], {'Data', 'something', strLegend(k)});
%Labeling graph
title('Plotting with polyfit and polyval');
end
0 Comments
Marco Riani
on 11 May 2020
Hi Carly
in your code just replace
legend('Data',strLegend(k));
with
legend({strLegend{k},'StringYouLike'})
Best
Marco
0 Comments
See Also
Categories
Find more on Legend 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!