Legend & Labeling points in a plot

조회 수: 19 (최근 30일)
rezheen
rezheen 2025년 5월 28일
댓글: Matt J 2025년 5월 28일
I'd like to have a legend that shows all tangent lines and curves of my graph, also label points if possible either in the legend or right next to the points themselves. My code doesn't do either currently:
syms a x
y=1/(x-1); m=-1; dy=diff(y);
x1_=subs(dy,a); eq=x1_==m; x1=solve(eq); y1=subs(y,x1);
line=m*(x-x1)+y1;
disp('The tangent line(s) are:')
The tangent line(s) are:
for k=1:length(x1)
fprintf('y = %s\n',char(line(k)))
f=plot(x1,y1,'.', 'color', 'black','markersize',15); hold on
g=fplot(line); set(g,'color','black','LineStyle', '--'); hold on;
end
y = - x - 1 y = 3 - x
h=fplot(y); set(h,'color','blue','Linewidth', 1);
j=xline(0); set(j,'color','black','Linewidth', 1.5)
k=yline(0); set(k,'color','black','Linewidth', 1.5)
xlabel('x'); ylabel('y'); title('Curve & tangent line & points')
legend([g h],{'Tangent line', 'Curve'})
Error using horzcat
Dimensions of arrays being concatenated are not consistent.
Thanks.

채택된 답변

Matt J
Matt J 2025년 5월 28일
편집: Matt J 2025년 5월 28일
syms a x
y=1/(x-1); m=-1; dy=diff(y);
x1_=subs(dy,a); eq=x1_==m; x1=solve(eq); y1=subs(y,x1);
line=m*(x-x1)+y1;
disp('The tangent line(s) are:')
The tangent line(s) are:
for k=1:length(x1)
fprintf('y = %s\n',char(line(k)))
f(k)=plot(x1(k),y1(k),'.', 'MarkerSize',15); hold on
g(k)=fplot(line(k),'--');
end
y = - x - 1 y = 3 - x
h=fplot(y,'color','blue','Linewidth', 1);
xline(0,'color','black','Linewidth', 1.5);
yline(0,'color','black','Linewidth', 1.5);
xlabel('x'); ylabel('y'); title('Curve & tangent line & points')
legend([g(:); f(:); h],{'Tangent line 1','Tangent line 2' ,'Point 1','Point 2', 'Curve'})
col={'red','green'};
[f.Color]=deal(col{:});
[g.Color]=deal(col{:});
hold off
  댓글 수: 6
rezheen
rezheen 2025년 5월 28일
That's great! But instead of labeling the points '1', '2', could it label what they actually are?
In this case (0, -1), (2, 1)
Matt J
Matt J 2025년 5월 28일
Yes, you can provide whatever labels you want. From the help doc,
% Hout=scatlabel(H,labels) %Provided labels can be string or numeric

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by