How to put a variable in a legend without it being in the range of the plot?

6 views (last 30 days)
When i try to place a variable in the legend of a plot, lets say the slope of a function. Even if I, from other examples use the sprintf(), I get Warning: Ignoring extra legend entries. What am I doing wrong? slope = 10000000000; x = 1:5; y = 6:10; a = 11:15; b = 16:20; slopestr = sprintf('slope is %f',slope); figure(1); plot(x,y); hold on; plot(a,b); legend('curve1','curve2',slopestr); hold off;
  1 Comment
Alexander Björkengren
Alexander Björkengren on 18 Nov 2022
I ended up plotting the variables with white color then changing the axes limits to get the original appearence. Then sprintf() worked fine for putting the variables in the legend

Sign in to comment.

Answers (1)

VBBV
VBBV on 18 Nov 2022
slope = 3;
x = 1:5;
y = 6:10;
a = 11:15;
b = 16:20;
slopestr = sprintf('slope is %f',slope)
slopestr = 'slope is 3.000000'
figure(1);
plot(x,y);
hold on;
plot(a,b);
plot(slope,'o')
legend('curve1','curve2',slopestr);
hold off;
  4 Comments
VBBV
VBBV on 18 Nov 2022
Edited: VBBV on 18 Nov 2022
you can plot the slope value in terms of log function, if you want all in one graph, since the value of slope is very large !
slope = 1e9; % a very high value
x = 1:5;
y = 6:10;
a = 11:15;
b = 16:20;
slopestr = sprintf('slope is %0.1f',slope)
slopestr = 'slope is 1000000000.0'
figure(1);
plot(x,y);
hold on;
plot(a,b);
plot(log(slope),'bo','markersize',8) % plot using log value of slope
text(min(x)+0.5,log(slope),'Slope')
% axis([0 15 0 1e9]) % this is not good option
legend('curve1','curve2',slopestr);
hold off;
VBBV
VBBV on 18 Nov 2022
you can try plotting x,y,a,b and slope variables in log function instead to represent all in one graph
slope = 1e9; % a very high value
x = 1:5;
y = 6:10;
a = 11:15;
b = 16:20;
slopestr = sprintf('slope is %0.1f',slope)
slopestr = 'slope is 1000000000.0'
figure(1);
semilogx(x,y);
hold on;
semilogx(a,b);
plot(log(slope),'bo','markersize',8) % plot using log value of slope
text(min(x)+0.1,log(slope),'Slope')
grid
% axis([0 15 0 1e9]) % this is not good option
legend('curve1','curve2',slopestr);
hold off;

Sign in to comment.

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!