Error when creating legend

12 次查看(过去 30 天)
Hi everyone
I am trying to print my legend on one of my figures as follows
legend('Signal', sprintf('Amplitude = %0.04d', 9.5971e-5 ), sprintf('RMS = %0.004d', 1.2894e-5 )
This prints my amplitude value but completely ignores the RMS value. Is there something I am doing wrong?
  1 个评论
AndresVar
AndresVar 2022-3-4
does it give you a warning? It looks like you only have 2 things plotted.
For example here I try to legend 2 things but there is only 1 plot so MATLAB gives warning.
figure;
plot(1:3);
legend('test','test2')
Warning: Ignoring extra legend entries.

请先登录,再进行评论。

采纳的回答

Voss
Voss 2022-3-4
If the RMS line is in the axes, then its legend entry should show up:
t = (1:500)*1e-8;
signal = randn(1,numel(t));
[amp,idx] = max(abs(signal));
signal_rms = rms(signal);
figure();
plot(t,signal);
hold on
plot(t(idx),signal(idx),'o');
yline(signal_rms);
legend('Signal', sprintf('Amplitude = %0.04d', amp ), sprintf('RMS = %0.004d', signal_rms ));
If the RMS line is is not in the axes, then its legend entry will not show up and you'll get a warning about extra legend entries:
figure();
plot(t,signal);
hold on
plot(t(idx),signal(idx),'o');
% yline(signal_rms);
legend('Signal', sprintf('Amplitude = %0.04d', amp ), sprintf('RMS = %0.004d', signal_rms ));
Warning: Ignoring extra legend entries.
My guess is the RMS line is not in the axes, perhaps due to a misplaced hold on.
  2 个评论
Image Analyst
Image Analyst 2022-3-4
Plotting a black line along the y=RMSValue level or along the x axis (y=0) is a good workaround to get the RMS to show up in the legend, if you prefer not to use text().
David Harra
David Harra 2022-3-4
Thanks, very helpful and appreciated

请先登录,再进行评论。

更多回答(2 个)

Image Analyst
Image Analyst 2022-3-4
编辑:Image Analyst 2022-3-4
It only prints as many legend items as there are things that you plotted. Since you only plotted two things, the blue curve and the red circles, only legends for those two items will show up no matter how many strings you feed into legend(). Look at it this way, if it DID plot some line/symbol combination for RMS, what would it use? A green triangle? Why? There is no green triangle plotted nor any other things other than the blue curve and the red circle. Since it can't figure out what to use, it just doesn't use those extra legend arguments.
If you want some other text on there, you can use the text() function. Like
str = sprintf('RMS = %0.9f', 1.2894e-5 )
text(1, -1, str);

Voss
Voss 2022-3-4
编辑:Voss 2022-3-4
Maybe you meant to do this:
data = randn(1,10);
[amp,idx] = max(data);
plot(data);
hold on
plot(idx,data(idx),'o');
legend('Signal', sprintf('Amplitude = %0.04d\nRMS = %0.004d', amp, rms(data)))

类别

Help CenterFile Exchange 中查找有关 Legend 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by