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

83 visualizaciones (últimos 30 días)
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!

Respuestas (2)

Scott MacKenzie
Scott MacKenzie el 30 de Mayo de 2021
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 comentarios
Scott MacKenzie
Scott MacKenzie el 30 de Mayo de 2021
Editada: Scott MacKenzie el 30 de Mayo de 2021
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.

Iniciar sesión para comentar.


Tony Greenwood
Tony Greenwood el 6 de En. de 2023
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,

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by