How to change line width of matlab legend without changing the other legend options?

100 次查看(过去 30 天)
I am trying to change the line width of a legend. I made it but in doing so I also changed the number of columns of my legend. Yet, I want them to stay fixed.
This is my code:
yyaxis left
plot(Time,Y,'LineWidth',2.2)
datetick('x', 'yyyy')
xlim([min(Time) max(Time)])
yline(2,'HandleVisibility','off')
yline(0,'HandleVisibility','off')
yyaxis right
plot(Time, y1, '--r', 'LineWidth',0.5)
hold on
plot(Time, y2, '--b', 'LineWidth',0.5)
hold on
plot(Time, y3, '--k','LineWidth',0.5)
datetick('x', 'yyyy')
xlim([min(Time) max(Time)])
ax = gca;
ax.YAxis(1).Color = 'k';
ax.YAxis(2).Color = 'k';
hold off
[~, hobj, ~, ~] = legend('X1','X2', 'X3','X4','Location','southoutside','NumColumns',2)
hl = findobj(hobj,'type','line');
set(hl,'LineWidth',0.8);
set(hl, 'NumColumns', 2) % here the error
Can anyone help me?
Thanks!

回答(2 个)

Scott MacKenzie
Scott MacKenzie 2021-5-30
I don't see the problem you note, re a change in the number of columns in the legend. The error occurs because you are trying to change a non-existent property of line objects. Just delete (or comment out) that line. The line width is controlled via the LineWidth propery of the legend's line objects. Below are demos for linewidths of 0.8 and 2:
set(hl,'LineWidth', o.8);
% set(hl, 'NumColumns', 2) % here the error
set(hl,'LineWidth', 2);
% set(hl, 'NumColumns', 2) % here the error
  3 个评论
Scott MacKenzie
Scott MacKenzie 2021-5-30
编辑:Scott MacKenzie 2021-5-30
Hmm, yes, I see your point. This might be related to the way you are using legend. doc legend (on my machine, R2021a) doesn't show the version you are using with a 4-value vector returned. It's possible this is an older version in which NumColumns isn't supported. Others might know better. But, here's a demo of what I am seeing...
[~, hobj, ~, ~] = legend('X1','X2', 'X3','X4','Location','southoutside','NumColumns',2)
% h = legend('X1','X2', 'X3','X4','Location','southoutside','NumColumns',2)
% [~, hobj, ~, ~] = legend('X1','X2', 'X3','X4','Location','southoutside','NumColumns',2)
h = legend('X1','X2', 'X3','X4','Location','southoutside','NumColumns',2)
See also Adam's answer here where the problem you are having is noted with a workaround offered.

请先登录,再进行评论。


Tony Greenwood
Tony Greenwood 2023-1-6
I have this issue, when I set the line width it seems as though the other legend options are ignored. So the position number of colums revert back to default and attempts to see these again don't seem to work,

类别

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