sgtitle的源代码
时间: 2023-10-13 15:21:18 浏览: 72
`sgtitle` 函数是 MATLAB 中用来添加图形对象的标题的函数。以下是其基本的源代码:
```matlab
function h = sgtitle(str,varargin)
%SGTITLE Put a title above all subplots.
% SGTITLE('text') adds text above all subplots.
% H = SGTITLE(...) returns the handle to the title.
%
% See also TITLE, SUPERTITLE.
% Clay M. Thompson 7-9-91, Revised 12-14-92 CMT
% Revised by Michael Robbins 8-16-93
% Revised by Steven L. Eddins, April 1997
% Revised by Chris Griffin, 3-27-03
% Parse the input arguments
[ax,args,nargs] = parseplotapi(varargin{:});
% Make sure all the axes are normalized
makeaxesfit(ax);
% Make sure the title string is a character vector
if ~ischar(str)
error(message('MATLAB:sgtitle:StringMustBeChar'));
end
str = str(:)';
% Find the parent figure for the given axes
fig = ancestor(ax(1),'figure');
% Create a new axes object to use as the title
title_ax = axes('Parent',fig,'Position',[0,0,1,1],'Visible','off');
set(title_ax,'XTick',[],'YTick',[]);
% Add the title string to the new axes object
h = text(0.5,1,str,'HorizontalAlignment','center','VerticalAlignment','top', ...
'FontSize',get(0,'DefaultAxesTitleFontSize'), ...
'FontWeight',get(0,'DefaultAxesTitleFontWeight'), ...
'Parent',title_ax);
% Adjust the vertical spacing between the title and the subplots
set(title_ax,'Units','normalized');
set(ax,'Units','normalized');
axpos = get(ax,'Position');
titlepos = get(title_ax,'Position');
titlepos(2) = max(axpos{1}(2)+axpos{1}(4),titlepos(2));
set(title_ax,'Position',titlepos);
% Fix the figure size, if necessary
fixfigureposition(fig);
% Return the title handle, if requested
if nargout > 0
h = h(1);
end
end
function fixfigureposition(fig)
%FIXFIGUREPOSITION Fix the size of the figure containing the given axes.
%
% FIXFIGUREPOSITION(FIG) fixes the size of the figure with handle FIG
% so that it contains all of the given axes.
% Calculate the new figure position
pos = [inf,inf,-inf,-inf];
ax = findobj(fig,'Type','axes','-not','Tag','legend','-and','Visible','on');
for i = 1:length(ax)
pos = min([pos;get(ax(i),'OuterPosition')]);
end
if isinf(pos(1)), return; end % No visible axes
pos(3:4) = pos(3:4) + pos(1:2);
pos(1:2) = [0,1];
% Set the new figure position
set(fig,'Units','pixels');
figpos = get(fig,'Position');
if any(pos(3:4) > figpos(3:4))
figpos(3:4) = max(pos(3:4),figpos(3:4));
set(fig,'Position',figpos);
end
end
function makeaxesfit(ax)
%MAKEAXESFIT Make sure all the given axes are normalized.
set(ax,'Units','normalized');
end
function [ax,args,nargs] = parseplotapi(varargin)
%PARSEPLOTAPI Parse the input arguments to the plot functions.
% Define the input argument types
argtypes = {'axes','char','cell','cell','cell','cell'};
% Parse the input arguments
[ax,args] = matlab.graphics.internal.makevalidinput(varargin,argtypes,mfilename);
% Count the number of non-axes arguments
nargs = length(args);
end
```
该函数的功能是在 MATLAB 的图形窗口中添加一个标题,该标题位于所有子图的上方。它使用 `text` 函数在新的 `axes` 对象中添加文本,并调整 `axes` 对象的位置以便与子图对齐。
阅读全文