Multiple lines for a single legend entry

조회 수: 109(최근 30일)
Szilard Novoth
Szilard Novoth 2020년 5월 5일
편집: Szilard Novoth 2021년 9월 6일
I was wondering if it is possible to add a single legend for multiple lines, like here:
Thank you in advance!
  댓글 수: 1
darova 2020년 5월 5일
I think it's impossible. One object - one legend

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

채택된 답변

David Neussl
David Neussl 2021년 9월 3일
Hi, i think i may have a solution for your problem. My approach was to "plot" invisible NaNs, give them the color i want and create legend entries for those NaNs.
For example: Lets say we have 6 lines (10 data points each), where the first 3 are of GROUP 1 and the last three are of GROUP 2:
data = rand(10,6);
cm = colormap('lines'); % Get default line colors
figure, hold on;
for i = 1:6
% Get index for line colors (GROUP1=1:3, GROUP2=4:6)
if i <= 3
colorindex = 1;
colorindex = 2;
% Turn HandleVisibility off to disable legend entries for these lines
plot(data(:,i), 'Color', cm(colorindex,:), 'HandleVisibility', 'off');
% These nans will be invisible
plot(NaN, 'DisplayName', 'GROUP 1', 'Color', cm(1,:));
plot(NaN, 'DisplayName', 'GROUP 2', 'Color', cm(2,:));
% Show legend
legend('Location', 'Best');
This then gives this plot as a result
  댓글 수: 1
Szilard Novoth
Szilard Novoth 2021년 9월 6일
편집: Szilard Novoth 2021년 9월 6일
That is a clever workaround, thank you :)
The perfect solution would be, if I could give a single legend for two (or more) different lines.
For example you have 3 red lines, but maybe I want to differentiate these lines by having one dashed and another one dotted, but still only have the legend GROUP 1
red ‘-‘, ‘:’, ‘.’ GROUP1
blue ‘-‘, ‘:’, ‘.’ GROUP2

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

추가 답변(0개)


Community Treasure Hunt

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

Start Hunting!

Translated by