function h = swarmchart(varargin)
%SWARMCHART Swarm chart.
%   SWARMCHART(x,y) displays a scatter plot where points are jittered in 
%   the x dimension based on an estimate of the  kernel density in the y 
%   dimension for each unique x. Swarm charts provide a visualization for
%   discrete x data that captures the distribution of y data. SWARMCHART 
%   sets the maximum jitter width to be 90% of the minimum difference 
%   between distinct values of x.
%   
%   SWARMCHART(x,y,sz) draws the markers at the specified sizes (sz)
%   SWARMCHART(x,y,sz,c) uses c to specify color, see SCATTER for a
%   description of how to manipulate color.
%
%   SWARMCHART(...,M) uses the marker M instead of 'o'.
%   SWARMCHART(...,'filled') fills the markers
%
%   SWARMCHART(AX,...) plots into AX instead of GCA.
%   S = SWARMCHART(...) returns handles to the scatter object created.
%
%   Example:
%       x=randi(4,1000,1);
%       y=randn(1000,1);
%       SWARMCHART(x,y)
%
%   See also SCATTER, SWARMCHART3, BUBBLECHART.

%   Copyright 2020 The MathWorks, Inc.
narginchk(2,inf)
cax=[];
if isa(varargin{1},'matlab.graphics.Graphics')
    cax=varargin{1};
    varargin(1)=[];
end

x=varargin{1};
if iscategorical(x)
    uniquex=1;
elseif ~isnumeric(x)
    error('MATLAB:scatter:InvalidSwarmXData', getString(message('MATLAB:scatter:InvalidSwarmData','X')))
else
    uniquex=unique(x);
end

if numel(uniquex)==1
    jitwidth=.9;
else
    jitwidth=.9*min(diff(uniquex));
end

try
    if isempty(cax)
        obj = scatter(varargin{:});
    else
        obj = scatter(cax, varargin{:});
    end
catch e
    throw(e);
end

if strcmp(obj.XJitterMode,'auto')
    obj.XJitter='density';
end
if strcmp(obj.XJitterWidthMode,'auto')
    obj.XJitterWidth=jitwidth;
end

if nargout > 0
    h = obj;
end

end