Plot circles with alpha values in MATLAB

后端 未结 5 1534
执念已碎
执念已碎 2020-12-16 23:30

I\'m creating a scatter plot of some data, as you do, and I have a number of repeated data points which I\'d like to plot as circles with some alpha value so that piling on

5条回答
  •  难免孤独
    2020-12-17 00:05

    I tried to do a general function using patch. It's slow and a bit buggy, but it works OK for simple cases. MATLAB needs a real-line alpha though.

    x and y are points to plot, w the width of the line, col the color and a the alpha value.

    Example:

    x = linspace(-2,2,100);
    plotWithAlpha(x,sin(4*x),0.04,'r',0.2)
    
    
    function [] = plotWithAlpha(x,y,w,col,a)
    %function [] = plotWithAlpha(x,y,w,col,a)
        if(size(x,1) ~= 1)
           x = x.';
        end
    
        if(size(x,1) ~= 1)
           y = y.';
        end
    
        sz = length(x);
    
        % Calculate derrivatives of the curve
        X = csaps(1:sz(1),x,1);
        Y = csaps(1:sz(1),y,1);
    
        mx = fnval(fnder(X,1),1:sz(1)).';
        my = fnval(fnder(Y,1),1:sz(1)).';
    
        T = [mx my]; %tangent
    
        % Normalize tangents
        T = bsxfun(@rdivide,T,sqrt(sum(T.^2,2)));
    
        N = zeros(size(T));
    
        N(:,2) = 1;
        N(:,1) = -T(:,2)./T(:,1);
    
        N = bsxfun(@rdivide,N,sqrt(sum(N.^2,2)));
    
        N = N.';
    
        hold on
    
        for i = 2:length(x)
            X = [x(i-1)+w*N(1,i-1) x(i)+w*N(1,i) x(i-1)-w*N(1,i-1) x(i)-w*N(1,i)];
            Y = [y(i-1)+w*N(2,i-1) y(i)+w*N(2,i) y(i-1)-w*N(2,i-1) y(i)-w*N(2,i)];
    
            % Order the points
            D = pdist([X' Y']);
            D = squareform(D); D(D==0) = Inf;
    
            inds = 1;
            D(:,1) = Inf;
    
            [val ind] = min(D(1,:));
            inds(2) = ind;
            D(:,ind) = Inf;
    
            [val ind] = min(D(ind,:));
            inds(3) = ind;
            D(:,ind) = Inf;
    
            inds(4) = setxor(inds,1:4);
    
            X = X(inds);
            Y = Y(inds);
    
            patch(X,Y,col,'edgeColor','none','FaceAlpha',a)
        end
    
        hold off
    

提交回复
热议问题