manually enter legend details

조회 수: 70 (최근 30일)
Aravind Krishna
Aravind Krishna 2017년 4월 7일
편집: David Angeles 2021년 9월 24일
I have 9 curves on a plot. 3 different colors x 3 (solid lines, dotted lines etc). However Instead of crowding my legend with 9 entries, I'd like to depict each color - their meaning (example red - 30-70Hz, blue - 20-50hz etc) and separately the meaning of dotted lines (training set), solid lines (test set) etc. How do I do this in Matlab ?

채택된 답변

Walter Roberson
Walter Roberson 2017년 4월 7일
  • You could put the information in a different area not using legend()
  • You could plot 6 additional lines with nan or inf as their coordinates, and using the bare style (e.g., just red with no dotting, or just solid with color not one of the three). Capture the handles of those and pass those to legend() so that only those lines would be legend()'d. With the nan or inf coordinates the lines will not be displayed, but they will exist enough for legend to be able to work with them. You would not legend() any of the real plot lines, because if you did that then legend() would want to display the combination style for them, color with spacing both.
  댓글 수: 2
Aravind Krishna
Aravind Krishna 2017년 4월 7일
Cool thanks, this circumvents the problem... So there is no absolute way of manually entering legend details.........
Walter Roberson
Walter Roberson 2017년 4월 7일
legend entries are tied to graphics objects in the axes, but you want to just enter information.
In R2014b and later, it became a lot more difficult to modify the way legends are drawn. Now, legends are handled completely internally by default. You can use the multi-output version of legend to have it create some of the graphics objects instead, but you are limited as to the changes you can make to those graphics objects.

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

추가 답변 (1개)

David Angeles
David Angeles 2021년 9월 24일
편집: David Angeles 2021년 9월 24일
Use the legend() function at the end of your plot with and empty string entry. Then, plot empty lines according to the final legend output you desire. Use 'DisplayName' to properly name the lines on the final legend output.
x = linspace(0,1, 10);
cols = ["red", "blue", "green"];
line_type = ["-", "--", ":"];
for i = 1:9
y = x + i/3;
col_i = cols(mod(i,3) + 1);
line_type_i = line_type(mod(i,3) + 1);
plot(x,y, line_type_i, 'Color', col_i)
hold on
end
legend('','Location', 'eastoutside')
col_names = ["30-70Hz", "20-50Hz", "40-80hz"];
for j =1:length(col_names)
plot([NaN NaN], [NaN NaN], 'Color', cols(j), 'DisplayName', col_names(j))
end
line_names = ["training set", "testing set", "simulation"];
for j =1:length(line_type)
plot([NaN NaN], [NaN NaN],line_type(j), 'Color', 'k', 'DisplayName', line_names(j))
end
hold off

카테고리

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