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

조회 수: 208 (최근 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