Having trouble with legend

1 vue (au cours des 30 derniers jours)
Carly Hudson
Carly Hudson le 11 Mai 2020
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.

Réponses (2)

Peng Li
Peng Li le 11 Mai 2020
Modifié(e) : Peng Li le 11 Mai 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

Marco Riani
Marco Riani le 11 Mai 2020
Hi Carly
in your code just replace
legend('Data',strLegend(k));
with
legend({strLegend{k},'StringYouLike'})
Best
Marco

Produits


Version

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by