function plot2(x,y, color, average, ploterrorbar, circlesizemx)
% function plot2(x,y, color, average, ploterrorbar, circlesizemx)
% scatter plot with circles, circle size is proportional to data size
%
% x, y: data x and y. If there are NaNs or Infs in the data, I will remove
% them first.
% color: the color of plot. either a character such as 'k', 'b', etc, or a
% vector [1 0.5 0.6] of RGB
% average: (0 or 1), do you want to average y if their corresponding x are
% same?
% ploterrorbar: (0 or 1), whether or not plot errorbar
% circlesizemx: an integer. default 5, this will be the upper bound of circle size
% 
% example:
%   x = [1 1 2 2 4 4 4 4 4 6 6 7 7 9 9 10 10];
%   y = [1 2 3 3 4 5 3 6 7 7 9 10 10 10 12 13 14];
%   plot2(x,y,'r', 1, 1)
%   plot2(x,y,[1 0 0]);
%
%   x = [1 2 4 4 4 6 7 7 9 10];
%   y = [0 0 0 1 0 0 1 1 1 1];
%   plot2(x,y,'r', 1)
%
% Xu Cui, 2005-12-12

% convert to column vector
[xc, xr] = size(x);
[yc, yr] = size(y);

if xc == 1
    x = x';
end

if yc == 1
    y = y';
end

% remove NaN
tmpposx = find(isnan(x) | isinf(x));
tmpposy = find(isnan(y) | isinf(y));
x([tmpposx; tmpposy]) = [];
y([tmpposx; tmpposy]) = [];

x = double(x);
y = double(y);
if exist('average')
    if average
        ux = unique(x);
        for ii=1:length(ux)
            pos = find(x==ux(ii));
            standarderror(ii) = std(y(pos))/sqrt(length(pos));
            y(pos) = mean(y(pos));
        end
    end
end

udata = unique([x y], 'rows');
N = size(udata,1);
circlesize = zeros(N,1);
singlePointPosition = [];
for ii=1:N
    tmp = find(x==udata(ii,1) & y==udata(ii,2));
    circlesize(ii) = length(tmp);
    if circlesize(ii) == 1
        singlePointPosition = [singlePointPosition ii];
    end
end

if ~exist('circlesizemx')
    circlesizemx = 5;    
end

circlesize = circlesize/max(circlesize)*circlesizemx*5;

if ~exist('color')
    color = 'b';
end

% if isstr(color)
%     colors='rbkmcgyrbkmcgyrbkmcgyrbkmcgyrbkmcgyrbkmcgyrbkmcgy';
%     pos = find(colors==color);
%     color = colors(pos(1)+1);
% end
if exist('ploterrorbar') == 1
    if(ploterrorbar == 1)        
        udata(singlePointPosition,:) = [];
        circlesize(singlePointPosition) = [];
        standarderror(singlePointPosition) = []; 
        x = udata(:,1);
        y = udata(:,2);               
        errorbar(x,y,standarderror,'color', color);
        hold on;
    end
end

h = scatter(udata(:,1),udata(:,2),circlesize*20,color, 'filled');
set(h, 'MarkerEdgeColor', color, 'MarkerFaceColor', 'w');