3D histogram with gnuplot or octave

后端 未结 5 513
余生分开走
余生分开走 2020-12-09 13:17

I would like to draw a 3D histogram (with gnuplot or octave) in order to represent my data. lets say that I have a data file in the following form:

2 3 4             


        
5条回答
  •  北海茫月
    2020-12-09 13:37

    I think the following should do the trick. I didn't use anything more sophisticated than colormap, surf and patch, which to my knowledge should all work as-is in Octave.

    The code:

    %# Your data
    Z = [2 3 4
        8 4 10
        5 6 7];
    
    
    %# the "nominal" bar (adjusted from cylinder())
    n = 4;
    r = [0.5; 0.5];
    m = length(r);
    theta = (0:n)/n*2*pi + pi/4;
    
    sintheta = sin(theta); sintheta(end) = sqrt(2)/2;
    
    x0 = r * cos(theta);
    y0 = r * sintheta;
    z0 = (0:m-1)'/(m-1) * ones(1,n+1);
    
    %# get data for current colormap
    map = colormap;
    Mz = max(Z(:));
    mz = min(Z(:));
    
    % Each "bar" is 1 surf and 1 patch
    for ii = 1:size(Z,1)
        for jj = 1:size(Z,2)
    
            % Get color (linear interpolation through current colormap)
            cI = (Z(ii,jj)-mz)*(size(map,1)-1)/(Mz-mz) + 1;
            fC = floor(cI);
            cC = ceil(cI);
            color = map(fC,:) + (map(cC,:) - map(fC,:)) * (cI-fC);
    
            % Translate and rescale the nominal bar
            x = x0+ii;
            y = y0+jj;
            z = z0*Z(ii,jj);
    
            % Draw the bar
            surf(x,y,z, 'Facecolor', color)
            patch(x(end,:), y(end,:), z(end,:), color)
    
        end
    end
    

    Result:

    enter image description here

    How I generate the "nominal bar" is based on code from MATLAB's cylinder(). One cool thing about that is you can very easily make much more funky-looking bars:

    enter image description here

    This was generated by changing

    n = 4;
    r = [0.5; 0.5];
    

    into

    n = 8;
    r = [0.5; 0.45; 0.2; 0.1; 0.2; 0.45; 0.5];
    

提交回复
热议问题