function [hh,ax] = pareto(y,names)
%PARETO Pareto chart.
%   PARETO(Y,NAMES) produces a Pareto chart where the values in the
%   vector Y are drawn as bars in descending order.  Each bar will
%   be labeled with the associated name in the string matrix or 
%   cell array NAMES.
%
%   PARETO(Y,X) labels each element of Y with the values from X.
%   PARETO(Y) labels each element of Y with its index.
%
%   [H,AX] = PARETO(...) returns a combination of patch and line object
%   handles in H and the handles to the two axes created in AX.
%
%   See also HIST, BAR.

%   Copyright 1984-2000 The MathWorks, Inc. 
%   $Revision: 1.21 $  $Date: 2000/06/02 04:30:50 $

hold_state = ishold;
if nargin==0,
  error('Not enough input arguments.');
end
if nargin==1,
  m = length(sprintf('%.0f',length(y)));
  names = reshape(sprintf(['%' int2str(m) '.0f'],1:length(y)),m,length(y))';
elseif nargin==2
  if iscell(names)
    names = char(names);
  elseif ~isstr(names)
    names = num2str(names(:));
  end
end

if (min(size(y))~=1),
   error('Y must be a vector.');
end
y = y(:);
[yy,ndx] = sort(y);
yy = flipud(yy); ndx = flipud(ndx);

ax = subplot('position',get(newplot,'position'));
h = bar(1:length(y),yy);
hold on
h = [h;plot(cumsum(yy))];
hold off
ysum = sum(yy);

ax = gca;
if ysum==0, ysum = eps; end
k = min(min(find(cumsum(yy)/ysum>.95)),10);

if isempty(k), k = min(length(y),10); end

set(ax,'xlim',[.5 k+.5])
set(ax,'xtick',1:k,'xticklabel',names(ndx,:),'ylim',[0 ysum])

raxis = axes('position',get(ax,'position'),'color','none', ...
             'xgrid','off','ygrid','off','YAxisLocation','right',...
             'xlim',get(ax,'xlim'),'ylim',get(ax,'ylim'));
yticks = get(ax,'ytick');
if max(yticks)<.9*ysum,
  yticks = unique([yticks,ysum]);
end
set(ax,'ytick',yticks)
s = '';
for i=1:length(yticks),
  s = strvcat(s,[int2str(round(yticks(i)/ysum*100)) '%']);
end
set(raxis,'ytick',yticks,'yticklabel',s,'xtick',[])
set(ax,'ytick',get(ax,'ytick'))
set(gcf,'currentaxes',ax)
if ~hold_state, hold off, set(gcf,'Nextplot','Replace'), end

if nargout>0, hh = h; ax = [ax raxis]; end


