Add header to legend columns

Hello everyone,
I'd like to add a header to each column of a legend, which I manually did by calling the legend function with the parameter ('Box','off') and adding a rectangle around the legend as well as a text box containing the headers in bold (see attached file). Unfortunately, the grid can be seen through the legend by this method. How can I achive a better looking result without the grid lines in the rectangle?
Thanks for your help!

7 件のコメント

Dyuman Joshi
Dyuman Joshi 2023 年 2 月 7 日
You can decrease the font-size of legend or change xticks/yticks.
Or do you want the Legend box to show above the grid in an opaque manner?
dj1du
dj1du 2023 年 2 月 7 日
The solution in an opaque manner could be working out for me perhaps, how can I do this?
Mathieu NOE
Mathieu NOE 2023 年 2 月 7 日
have you looked on the file exchange ? there are improved legend submissions that can do what you are loocking for
Dyuman Joshi
Dyuman Joshi 2023 年 2 月 16 日
編集済み: Dyuman Joshi 2023 年 2 月 16 日
Does this work for you?
x = 0:0.01:10;
s=sin(x);
c=cos(x);
plot(x,s,x,c,x,s+c,x,s.*c,x,s-c,x,c-s)
grid on
ylim([-2.5 3.5])
l=legend({'sin', 'cos', 'sin+cos', 'sin*cos', 'sin-cos', 'cos-sin'}, 'Location', 'NorthWest', 'NumColumns', 2);
t=title(l,'plate: cylinder: ');
dj1du
dj1du 2023 年 2 月 16 日
This is almost perfect, but is there any way to hide/remove the line separating header and legend?
Sulaymon Eshkabilov
Sulaymon Eshkabilov 2023 年 2 月 16 日
Use:
legend('box', 'off') % Get rid off the box and line
Dyuman Joshi
Dyuman Joshi 2023 年 2 月 16 日
There doesn't seem any way to remove that particular line.
The only other way seems to be, is that you draw two white lines and name their legend 'plate:' and 'cylinder:' to get what you want. Even in that case, alignment will be different.
x = 0:0.01:10;
s=sin(x);
c=cos(x);
plot(x,x*0,'w',x,s,x,c,x,s+c,x,x*0,'w',x,s.*c,x,s-c,x,c-s)
grid on
ylim([-2.5 3.5])
l=legend({'plate:', 'sin', 'cos', 'sin+cos', 'cylinder:','sin*cos', 'sin-cos', 'cos-sin'}, 'Location', 'NorthWest', 'NumColumns', 2);
%t=title(l,'plate: cylinder: ');

サインインしてコメントする。

回答 (1 件)

Raghvi
Raghvi 2023 年 2 月 16 日

0 投票

Hey,
Although it doesn’t create the desired spacing, you can try out the following piece of code:
lgd = legend({'1->2','3->4','1->2','3->4'},...
'Location','northwest','NumColumns',2);
title(lgd,['plate: ' 'cylinder:'])
Alternatively, you can work around by using two different legends for the different lines all together and provide them both with a separate title using the title function.
Refer to the following MATLAB Answer to understand how to do so:

カテゴリ

タグ

質問済み:

2023 年 2 月 7 日

コメント済み:

2023 年 2 月 16 日

Community Treasure Hunt

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

Start Hunting!

Translated by