Having trouble with legend

조회 수: 1 (최근 30일)
Carly Hudson
Carly Hudson 2020년 5월 11일
답변: Marco Riani 2020년 5월 11일
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.

답변 (2개)

Peng Li
Peng Li 2020년 5월 11일
편집: Peng Li 2020년 5월 11일
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 2020년 5월 11일
Hi Carly
in your code just replace
legend('Data',strLegend(k));
with
legend({strLegend{k},'StringYouLike'})
Best
Marco

카테고리

Help CenterFile Exchange에서 Legend에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by