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

135 ビュー (過去 30 日間)
Armando MAROZZI
Armando MAROZZI 2021 年 5 月 30 日
回答済み: Tony Greenwood 2023 年 1 月 6 日
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.
Armando MAROZZI
Armando MAROZZI 2021 年 5 月 30 日
thanks a lot for your help!

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


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 Center および File ExchangeLegend についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by