Add titles over rows in subplots

189 次查看(过去 30 天)
Hi,
I have a figure with 8 subplots, arranged in two rows. I need to generate an automated code adding a centered title above each row, but fail to do so.
A sample code to illustrate the configuration (I also have annotations):
clf;
m = 2;
n = 4;
p = 1;
for i = 1:m*n
s(i) = subplot(m,n,p);
ant(i) = annotation('textbox',s(i).Position,'String',[num2str(i)+")"],...
'linestyle', 'none','Fontsize',14,'FontWeight','bold');
p = p + 1;
end
I want to place the titles without explictly give coordinates, i.e. something like titlehandle.position=[1 2 3 4] is not good, because I sometime use different computers/monitors/OS and the output is not consistent.
Thanks!

采纳的回答

Adam Danz
Adam Danz 2021-2-4
编辑:Adam Danz 2024-6-14
Create one centered title per row of subplots
Three methods are included
  • Subplot with an odd number of columns
  • Subplot with an even number of columns
  • Tiledlayout (most robust) Preferred method
Subplot with an odd number of columns
Add the title to the middle subplot
Demo:
figure()
subplotLayout = [3,3];
ax = gobjects(fliplr(subplotLayout));
for i = 1:prod(subplotLayout)
ax(i) = subplot(subplotLayout(1),subplotLayout(2),i);
end
ax = ax'; % now axis handles are same shape as subplot layout
% list all titles in order (top to bottom)
titles = {'Row 1 title', 'Row 2 title', 'Row 3 title'};
% Get handles to center subplots
centerSubHandles = ax(:,ceil(subplotLayout(2)/2));
for i = 1:numel(centerSubHandles)
% get center subplot handle
title(centerSubHandles(i), titles{i})
end
Subplot with an even number of columns
Compute the upper position of each row of subplots in normalized units and the center position across the first row of subplots (assuming the center position is the same for all rows of subplots). Then use annotation to set the title position.
Demo:
figure()
subplotLayout = [3,4];
ax = gobjects(fliplr(subplotLayout));
for i = 1:prod(subplotLayout)
ax(i) = subplot(subplotLayout(1),subplotLayout(2),i);
end
set(ax,'Units','Normalize') % this is typically the default
ax = ax'; % now axis handles are same shape as subplot layout
% Reduce vertical space of axes just a bit to make room for "titles"
axPos = cell2mat(get(ax, 'Position'));
axPos(:,4) = axPos(:,4).*.96; % reduces vert space to 96% of height
set(ax, {'Position'}, mat2cell(axPos, ones(numel(ax),1), 4))
% Get upper position of each row of axes, normalized coordinates
axPos = cell2mat(get(ax(:,1), 'Position'));
axUpperPos = sum(axPos(:,[2,4]),2); %upper pos.
% Get center position for 1st row (assumes all rows have same center)
axPos = cell2mat(get(ax(1,[1,end]),'Position'));
axCenterPos = mean([axPos(1,1), sum(axPos(2,[1,3]))]);
% list all titles in order (top to bottom)
titles = {'Row 1 title', 'Row 2 title', 'Row 3 title'};
% Set annotation for each row of subplots
titleHandles = gobjects(numel(titles),1);
for i = 1:numel(titles)
titleHandles = annotation('textbox','String',titles{i}, ...
'Position', [axCenterPos, axUpperPos(i), 0, 0], ...
'HorizontalAlignment', 'center','VerticalAlignment','bottom',...
'LineStyle','none','FitBoxToText','on', ...
'FontWeight',ax(1).Title.FontWeight, ... % matches title property
'FontSize', ax(1).Title.FontSize, ... % matches title property
'FontName', ax(1).Title.FontName, ... % matches title property
'Color', ax(1).Title.Color); % matches title property
end
Tiledlayout (most robust, preferred method)
Added 24-April-2023
tiledlayout creates a TiledChartLayout object which can contain an array of axes, similar to subplot. But TiledChartLayout objects can also host a global title centered above the array of subplots.
Nest a TiledChartLayout for each row of axes and then assign a title to each row. This way you're actually using a title object rather than text.
axgrid = [3,4]; % [#rows, #cols]
titles = {'Row 1 title', 'Row 2 title', 'Row 3 title'};
figure()
tclMain = tiledlayout(axgrid(1),1);
tcl = gobjects(1,axgrid(1));
ax = gobjects(axgrid);
for j = 1:numel(tcl)
tcl(j) = tiledlayout(tclMain,1,axgrid(2));
tcl(j).Layout.Tile = j;
for i = 1:axgrid(2)
ax(j,i) = nexttile(tcl(j));
end
title(tcl(j),titles{j})
end
Create one global title per column
If the inidividual tiles do not have titles, the easiest approach would be to assign a title to the axes in the top row (assuming you're using a fixed layout).
If your axes do have titles and you want to add global titles for each column, you can use a nested tiledlayout approach demonstrated below.
axgrid = [3,4]; % [#rows, #cols]
titles = {'Col 1 title', 'Col 2 title', 'Col 3 title', 'Col 4 title'};
figure()
tclMain = tiledlayout(1,axgrid(2));
tcl = gobjects(1,axgrid(2));
ax = gobjects(axgrid);
for j = 1:numel(tcl)
tcl(j) = tiledlayout(tclMain,axgrid(1),1);
tcl(j).Layout.Tile = j;
for i = 1:axgrid(1)
ax(j,i) = nexttile(tcl(j));
title(sprintf('Tile %d',ax(j,i).Layout.Tile))
end
title(tcl(j),titles{j})
end
  15 个评论
Adam Danz
Adam Danz 2024-6-14
@David Gonzalez, I've updated my answer to add the demo "Create one global title per column". It's similar to "Tiledlayout (most robust, preferred method)".

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Axis Labels 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by