How to change the number of columns in legend while changing the line thickness?

33 views (last 30 days)
I wanted to change the number of columns of my legend, while changing the thickness of the plots lines inside the legend without changing the plots thickness. I found the solution to change the line thickness here "How do i change the linewidth and the fontsize in a legend". However, when using this method the legend appears to have 1 column regardless of the input value. The code that doesn't work is:
[~, hobj, ~, ~] = legend(finLegend,'NumColumns', 3,'Location','best');
hl = findobj(hobj,'type','line');
set(hl,'LineWidth',5);
And the code that worked before, but didn't change the line thickness, was:
lgd = legend(finLegend,'NumColumns',3,'Location','best');
I don't understand why changing from a single to multiple outputs doesn't let me change the number of columns. Using property inspector the "NumColumns" property is 3, but the actual legend has one column.

Accepted Answer

Walter Roberson
Walter Roberson on 23 May 2023
I don't understand why changing from a single to multiple outputs doesn't let me change the number of columns.
The use of more than one output for legend invokes legacy behaviour for legend, and the legacy behaviour does not support multiple columns. The legacy behaviour is pretty much frozen at R2014b behaviour, but multiple columns for legends was added after that.
You will need to fake the legends. For each line that is to be made thicker for legend purposes, create a fake line with coordinates NaN, NaN, and with the same DisplayName and Color and LineStyle (and possibly marker information), but different LineWidth, and substitute the new handle for the old one in the list passed as the first parameter to legend() . You might find it easiest to copyobj() and set the XData and YData and LineWidth in the copy.
  1 Comment
George S
George S on 25 May 2023
Thank you, it works! I chose to use copyobj() and set the properties there, as I found the code to copy in another answer, here: '"How to change the line thickness inside the legend box ?". I hope Matlab makes it an option to change the line thickness of the legend in the future, as I find that many people struggle to see the line colours as they are so thin, but they don't want to make the plot lines thicker

Sign in to comment.

More Answers (0)

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!