%% Animate 3D Bivariate Histogram

figure                                                  % new figure
colormap cool                                           % set colormap
histogram2(vandalism.X, vandalism.Y, ...                % plot 3D bivariate 
    xbinedges, ybinedges, ...                           % histogram
    'FaceColor', 'flat', ...
    'DisplayStyle', 'bar3', ...
    'FaceAlpha', 0.5, 'EdgeAlpha', 0.5)
hold on                                                 % don't overwrite
image(lim.lon,lim.lat,map)                              % add the map
hold off                                                % restore default                       
ax = gca;                                               % get current axes handle
ax.CLim = [0 100];                                      % color axis scaling
ax.XAxis.Visible = 'off';                               % hide x-axis 
ax.YAxis.Visible = 'off';                               % hide y-axis
ax.ZAxis.Visible = 'off';                               % hide z-axis
title({'San Francisco Crime Map'; ...                   % add title
    'Vandalism: Jan 2003 - May 2015'}) 

axis vis3d                                              % freeze aspect ratio
ctr = [xbinedges(71),ybinedges(57),1145/2];             % set center
t = linspace(-1.6*pi/2,pi/2,128);                       % animation time
dx = 1.2*cos(t) + ctr(1);                               % cam x
dy = 0.9*sin(t) + ctr(2);                               % cam y
dz = 50*fliplr(t) + 5000;                               % cam z
ax.CameraPosition = [dx(1),dy(1),dz(1)];                % set cam positoin
ax.CameraTarget = ctr;                                  % target center

%% Uncomment to Generate Animated GIF
% first = true;                                           % flag
for i = 1:length(t)-5                                   % animate
    ax.CameraPosition = [dx(i),dy(i),dz(i)];            % update cam postion
    pause(0.1)                                          % pause 0.1 sec
%     fname = getframe(gcf);                              % get the frame
%     [x,cmap] = rgb2ind(fname.cdata, 128);               % get indexed image
%     if first                                            % if first frame
%         first = false;                                  % update flag
%         imwrite(x,cmap, 'html/rotateVand.gif', ...      % save as GIF
%             'Loopcount', Inf, ...                       % loop animation
%             'DelayTime', 0.5);                          % 2 frame per second
%     else                                                % if image exists
%         imwrite(x,cmap, 'html/rotateVand.gif', ...      % append frame
%             'WriteMode', 'append', 'DelayTime', 0.5);   % to the image
%     end
end