function hout = plot(varargin)
%PLOT Summary plot of regression model
%   PLOT(LM) produces a summary plot of the LinearModel LM.
%
%   If LM has exactly one predictor, the plot is a plot of the response as
%   a function of the predictor, with the fit and confidence bounds
%   superimposed.
%
%   If LM has more than one predictor, the plot is an added variable plot
%   for the model as a whole. If LM has no predictors, the plot is a
%   histogram of residuals.
%
%   H = PLOT(LM) returns a vector H of handles to the lines in the plot.
%
%   PLOT(AX,...) plots into the axes with handle AX.
%
%   The LM argument can be followed by name-value pairs to specify
%   properties of the lines in the plot, such as 'LineWidth' and 'Color'.
%
%    Example:
%       % Plot of census data with fitted quadratic curve
%       load census
%       lm = fitlm(cdate,pop,'quadratic');
%       plot(lm)
%
%   See also LinearModel, plotAdded.

%   Copyright 2020-2023 The MathWorks, Inc.

[ax, varargin] = matlab.graphics.chart.internal.inputparsingutils.peelFirstArgParent(varargin);
lm = varargin{1};
varargin = varargin(2:end);

% Check if axes is a second argument. Note that if the function is called like
% lm.plot(ax), the first argument will be 'lm' and second will be 'ax'.
if isempty(ax)
    [ax, varargin] =  matlab.graphics.chart.internal.inputparsingutils.peelFirstArgParent(varargin);
end

% Parse the set of NV args to see if there is a 'Parent' NV arg. If not,
% and an axes was provided, appened 'Parent' with the given axes to the NV
% arg list
[varargin{:}] = convertStringsToChars(varargin{:});
varargin = classreg.regr.modelutils.parseParentAxesNVArg(ax, varargin);

compactNotAllowed(lm,'plot',false);
p = length(lm.PredictorNames);
internal.stats.plotargchk(varargin{:});

if p==0
    % No predictors, plot residuals
    h = plotResiduals(lm,'histogram', varargin{:});
elseif p==1
    % One predictor, plot x vs y with fit and confidence bounds
    h = plotxy(lm,varargin{:});
else
    h = plotAdded(lm,[],varargin{:});
end

if nargout>0
    hout = h;
end
end