One combined legend entry for multiple plots
Asked Answered
D

1

1

For some reason, I would like to plot the line and marker of the same data separately.

data1 = (1:1:10)';
data2 = (1:2:10);
figure(1);
plot(data1,data1,'or');
hold on;
plot(data2,data2,'-r');
legend('data');

However it will only display the legend for the first plot. And Matlab seems not to have option to manipulate the legend marker, color and linestyle. enter image description here

How can I make legend like this?

enter image description here

Thanks!

Dorsal answered 2/3, 2015 at 20:23 Comment(5)
You can manipulate anything about legends using output arguments. Look for the icons variable when calling legend like so: [h,icons,plots,str] = legend(___)Outguard
Great! I must say that I did not understand you question very well except for the "manipulate legend marker part" haha :)Outguard
Yeah I'm deleting my answer as I seem to have misunderstood what the OP wants. Good going @Outguard !Grantgranta
I was exercising my mentalist skills @Grantgranta :)Outguard
@Outguard - lololol.Grantgranta
C
5

You will need to plot an invisible third plot (with almost no data to keep it fast) to define your legend:

data1 = (1:1:10)';
data2 = (1:2:10);
figure(1);
plot(data1,data1,'or'); hold on
plot(data2,data2,'-r'); hold on

%// legend plot
lp = plot(0,0,'-r','Marker','o','visible','off')
legend(lp,'data');

enter image description here

You need to pass the handle of that invisible plot to the legend command or you could even put the invisible plot into the legend:

legend(plot(0,0,'-r','Marker','o','visible','off'),'data');

If you need that more often, you can write a little helper function

style = @(LineStyle, MarkerStyle) plot(0,0,LineStyle,'Marker',MarkerStyle,'visible','off')
legend(style('-r','o'),'data');

... which you can customize with 'color', 'LineWidth' or whatever you want.

It enables you to create fully customized legends with multiple entries independently from your actually data:

legend([style('-r','o'),style('-b','x'),style('-g','v')],{'1','2','3'});

enter image description here

Cambridge answered 2/3, 2015 at 21:21 Comment(3)
Very nice. BTW congrats on 10K!Grantgranta
Hey! Congrats on that!!Argumentation
@thewaywewalk Congrats!Braxy

© 2022 - 2024 — McMap. All rights reserved.