Multiple lines for a single legend entry
117 ビュー (過去 30 日間)
古いコメントを表示
Hi!
I was wondering if it is possible to add a single legend for multiple lines, like here:
Thank you in advance!
採用された回答
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;
else
colorindex = 2;
end
% Turn HandleVisibility off to disable legend entries for these lines
plot(data(:,i), 'Color', cm(colorindex,:), 'HandleVisibility', 'off');
end
% 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
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Legend についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!