Creating a Tabular Legend
古いコメントを表示
I would like to create a legend with an additional column for a number to be inserted next to the variable name as follows:

However, I'm unsure as to how I can achieve this layout - I have tried searching for a function like gridlegend, but I cannot get it to work in this format. Any ideas as to how I can get this implemented? Thanks in advance.
採用された回答
その他の回答 (2 件)
Ameer Hamza
2020 年 4 月 22 日
Try this
ax = axes();
hold(ax);
plot(rand(1,10), 'LineWidth', 2);
plot(rand(1,10), 'LineWidth', 2);
plot(rand(1,10), 'LineWidth', 2);
labels1 = {'boot', 'engine', 'wheel'};
labels2 = {'1', '3', '5'};
labels = cellfun(@(x,y) {sprintf('%10s%9s', x, y)}, labels1, labels2);
l = legend(labels, ...
'FontName', 'FixedWidth');
titles = {'Line', 'Location', 'Number'};
titles = sprintf('%4s%14s%10s', titles{:});
l.Title.String = titles;

@Ameer Hamza Thanks for providing the code snippet and the solution — it's great. Unfortunately, it doesn’t solve my problem because I lose the handles to the plot objects.
I need a solution for two Y-axes using yyaxis left/right, so I’d like to share my workaround as well.
(I’ve removed unnecessary formatting.)
I’m using MATLAB R2025b, while the compiler at the forum is using MATLAB R2025a.
fig1 = figure(1);
ax1 = axes(fig1);
% Left axis time values
yyaxis left
% Plot
p1 = plot(ax1,rand(1,10), 'LineWidth', 2,'LineStyle',':');
hold on
p2 = plot(ax1,rand(1,10), 'LineWidth', 2,'LineStyle',':');
% Plot propperties
ylabel(ax1,'Lable 1')
yyaxis right
p3 = plot(ax1,rand(1,10), 'LineWidth', 2,'LineStyle','--');
hold on
p4 = plot(ax1,rand(1,10), 'LineWidth', 2,'LineStyle','--');
xlabel(ax1,'X-Label')
ylabel(ax1,'Lable 2')
title(ax1,'My Title}')
plotHandle = [p1,p2,p3,p4];
labels = {'Left_1','Left_2','Right_1','Right_2'};
leg = legend(ax1,plotHandle,labels,'NumColumns',2);
titles = {'left Y-axis', 'right Y-axis'};
titles = sprintf('%25s%25s', titles{:});
leg.Title.String = titles;
カテゴリ
ヘルプ センター および File Exchange で Title についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
