File Exchange

image thumbnail

Create Video of Rotating 3D Plot

version (810 KB) by Alan Jennings
Specify a set of view angles and this function creates a video for use in presentations.


Updated 03 Apr 2013

View License

CaptureFigVid(ViewZ, FileName,OptionZ)
Captures a video of the 3D plot in the current axis as it rotates based on ViewZ and saves it as 'FileName.mpg'. Option can be specified.

ViewZ: N-rows with 2 columns, each row are the view angles in degrees, First column is azimuth (pan), Second is elevation (tilt) values outside of 0-360 wrap without error,
*If a duration is specified, angles are used as nodes and views are equally spaced between them (other interpolation could be implemented, if someone feels so ambitious).
*If only an initial and final view is given, and no duration, then the default is 100 frames.
FileName: Name of the file of the produced animation. Because I wrote the program, I get to pick my default of mpg-4, and the file extension .mpg will be appended, even if the filename includes another file extension. File is saved in the working directory.
(OptionZ): Optional input to specify parameters. The ones I use are given below. Feel free to add your own. Any or all fields can be used
OptionZ.FrameRate: Specify the frame rate of the final video (e.g. 30;)
OptionZ.Duration: Specify the length of video in seconds (overrides spacing of view angles) (e.g. 3.5;)
OptionZ.Periodic: Logical to indicate if the video should be periodic. Using this removed the final view so that when the video repeats the initial and final view are not the same. Avoids having to find the interval between view angles. (e.g. true;)

% % % Example (shown in published results, video attached) % % % %
daspect([1,1,.3]);axis tight;
CaptureFigVid([-20,10;-110,10;-190,80;-290,10;-380,10], 'WellMadeVid',OptionZ)

Known issues:
MPEG-4 video option only available on Windows machines. See fix where the VideoWriter is called.

Getframe is used to capture image and current figure must be on monitor 1 if multiple displays are used. Does not work if no display is used.

Active windows that overlay the figure are captured in the movie. Set up the current figure prior to calling the function. If you don't specify properties, such as tick marks and aspect ratios, they will likely change with the rotation for an undesirable effect.

Cheers, Dr. Alan Jennings

Cite As

Alan Jennings (2021). Create Video of Rotating 3D Plot (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (66)

Ajay Goyal

WOW! incredible

F Farnoud

stewart lake


Jens Weise

Laura Edmondson

Alexander Collins

Lameck Amugongo

How can I create one video rotating two subplots.

fig = figure(100);clf;
trisurf(fv.faces, fv.vertices(:,1), fv.vertices(:,2), fv.vertices(:,3), insideChange);
axis equal;
shading flat;
colorbar('Ticks',[0,0.25,0.5,0.75,1,1.25,1.5,1.75,2], ...
'TickLabels',{'-100%','-75%','-50%', '-25%','No change', '+25%','+50%','+75%%', '+100%'});
title(strcat('Inside ', {' '}, foldername));
axis tight;
CaptureFigVid([-20,10;-110,10;-190,80;-290,10;-380,10], ['/Users/h62343la/Documents/Videos/' foldername], OptionZ)
% saveas(gcf,['/Users/h62343la/Documents/ChangeOverTimeGifs' '/' foldername '_inside' '.png'])

trisurf(fv.faces, fv.vertices(:,1), fv.vertices(:,2), fv.vertices(:,3), outsideChange);
axis equal;
shading flat;
colorbar('Ticks',[0,0.25,0.5,0.75,1,1.25,1.5,1.75,2], ...
'TickLabels',{'-100%','-75%','-50%', '-25%','No change', '+25%','+50%','+75%%', '+100%'});
title(strcat('Outside ', {' '}, foldername));
axis tight;
% Set up recording parameters (optional), and record
CaptureFigVid([-20,10;-110,10;-190,80;-290,10;-380,10], ['/Users/h62343la/Documents/Videos/' foldername], OptionZ)

Adam Clarke

Tuhin Choudhury

Ethan Kyzivat

Giao Vu

Jorge Arroyo



Stefan Dukic

Paulo Aguiar


Riya Dey

I want to generate some sphere in three dimension space. While running the program, the video can be seen in matlab plotting window , but the mp4 file shows only the initial capture, no video is shown there. Kindly help me to find out the issue.

The program is given below:

[x y z] = sphere;
a=[3 3 3 3;-3 -3 -3 3]
hold on
daspect([1 1 1])
axis tight;
CaptureFigVid([-20,10;-110,10;-190,80;-290,10;-380,10], 'video',OptionZ)

Brett Thomas

Tyler Smith

Great Function!

If anyone else had a problem with the the zoom pumping, just put:

ax = gca;
axis equal;

...prior to the function.

Loïc Toraille

Dean Rusby

babita Verma

Thanks Alan for the wonderful script!
But the axis label in the video does not seem to be moving along with axis, they seem to move slower and hence axis label appear to be randomly floating in the video. Also the example video does not have any axis label.Is there any way to fix this?

Osman Akar

Pages Nathan

Foisal Ahmed

Thanks a lot for your extraordinary work....


Amazingly simple, usable and powerful. Thanks!

Xiaoting Zhong

Thanks for sharing such a nice script!



Really great! Straightforward, does exactly what I wanted and only took a few seconds to set up. Thanks so much!




Jake Marvin

Sumantra Sarkar

Nat anunta


Thanks for this very nice code!!

Jordy W

Thanks! This is exactly what I was looking for.

Yamuna Maccarana


It's awesome function.
Thank you Dr. Alan Jennings for the awesome code.

Gregory Czarnota

Juan Baeza

leo nidas

Adding transparency (alpha(0.3)) is not working for me. Is there a tunraround? See example below. Even though it seems that the necessary frames are captured, the final movie file only shows a still image. Thanks.

%% Set up 3D plot to record
daspect([1,1,.3]);axis tight;
%% Set up recording parameters (optional), and record
CaptureFigVid([-20,10;-110,10;-190,80;-290,10;-380,10], 'WellMadeVid',OptionZ)

Jessica Benjamin

Also (apologies for bombarding with comments/questions) is there a way to make the background white? I've used:


but it doesn't seem to be working and returns to grey in the video?

Jessica Benjamin

This is such a clear code and has helped so much - thank you. Just wondered if you had any tips - I'm making a rotating video of a 3D mesh for a presentation and would like it to keep looping through. When I use the 'loop' feature in powerpoint there's always a short pause before it restarts - any idea how to avoid that issue?

Lucy Robinson

Hongkai Dai

Very clear written code. Thanks

Omid Hoseini

Great code. Thanks.

Omid Hoseini

Charles Dunn

This code worked perfectly on first use. Well documented. Thank you!

Alan Jennings

Hi Richard,
Thanks for adding the quote from the help file. I've seen getframe 'glitch' in some cases, but never had the opportunity (or motivation) to really track down how they crop up and are resolved on different platforms.
- Alan

Apparently, I can't do multiple comments on the same day...

Hi Thai, Glad it helps!
You could add another field for OptionZ for specifying the frame size. I don't think there's a great way of doing this in general. The way I normally do it, is to size the figure and then crop the matrix from getframe:
A_temp = getframe(gcf);
A_temp = A_temp(OptionZ.fWidth(1):OptionZ.fWidth(end),OptionZ.fHeight(1):OptionZ.fHeight(end))
I don't have MATLAB here, so there's a good chance there's some typos here. I often get the width and height mixed up.
HTH, Alan

Richard Edmonds

Hi, as per the help on getframe. "Setting the figure Renderer property to zbuffer or painters works around limitations of using getframe with the OpenGL renderer on some Windows® systems." Doing this solved the "static image" problem found by Christian Jensen below.

Thai V. Hoang

Great contribution!
Can we specify the frame size from the scripts?

Vasily Ruzov

Great job! Great script and great videos!

Adam Erickson

Thank you, Alan. I thought that might be the case. Post-processing using After Effects video stabilization might offer a good solution without a major re-write, which is what I will try now. Mayavi in Python is also pretty smooth and offers a nice alternative.

Alan Jennings

Hi Adam,
The short answer is, you don't make it better. Sorry.
MATLAB 3d plots and patches have always had some issues. I thought if I'd try hard enough, I could fix them, but it's just not the tool for that, just like you wouldn't want to make animations in PowerPoint.

The two main issues I've seen are the aspect ratio and limit jumping around for 3d plots (what I think you are referring to), and order/overlap being in the wrong order.
You can manual set the axes limit, axes pixel limits and aspect ratio every frame, but it's a whole lot of work to make it looks better, and sometimes perfect is impossible. The other issue is that based on the 3d location, some meshes should be hid by other meshes, but instead they are shown on top. I don't think the order you plot them affects this, but it's been a while and I don't remember. My suggestion is to change the renderer.

Hope this helps, Alan

Adam Erickson

Hi Alan,

Thank you for the excellent script! I'm getting very smooth video with point plots, but the mesh plots have a lot of jiggling to them, which ends up looking like camera vibration. How can I fix this?


Lazaros Moysis

Thanks for your reply! that helped me for sure! Changing the rating to 5.

Alan Jennings

Glad it helped Lazaros!
To make it bigger, just make the figure window bigger.
If you’re having issues with the compressions with the ‘MPEG’ format, you can add a quality factor, but the default of 75 (of 100) normally works good for me.
Add the following lines to the function, CaptureFigVid.m
Line 72:
if isfield(OptionZ,'Quality')
And then from where you call it, add

Lazaros Moysis

Can you specify the size of the video to upgrade the quality and make it better looking?



Can you help me transform this function
function Graf1()
for i = 1:length(x)
for j = 1:length(y)
if (a*abs(x(i))) <= abs(y(j))
z(i,j) = abs(y(j))
if (( abs(x(i)) <= abs(y(j)) ) && ( abs(y(j)) <= a*abs(x(i))))
z(i,j) = a*abs(x(i));
if (b*abs(y(j))) <= abs(x(i))
z(i,j) = abs(x(i))
if (( abs(y(j)) <= abs(x(i)) ) && ( abs(x(i)) <= b*abs(y(j))))
z(i,j) = b*abs(y(j))



title ('Plot Title', 'FontWeight','Bold','FontSize',11) % Add labels...
xlabel ('X Axis Label', 'FontWeight','Bold','FontSize',11)
ylabel ('Y Axis Label', 'FontWeight','Bold','FontSize',11)
zlabel ('Z Axis Label', 'FontWeight','Bold','FontSize',11)
grid on ; % Switch on the figure grid, and
set(gca,'GridLineStyle','-') % set the grid to solid li

I do not understand how can I rotate my graph drawing function.

Thank you !!! :)

Christian Jensen

If I don't include (...,'FaceLighting','phong')
in my surf plot, the figure spins but the movie is just one static image. Why is that?


Thanks! A couple of bugs/ideas:

1. You should make it an option to fix the "zoom pumping", maybe it is the camera position, that rotation the plot under a larger elevation (say 45°) does not cause the plot to zoom in and out in every quadrant while rotating. Try this to see what I mean:

CaptureFigVid([0,45;-359,45], 'WellMadeVid',OptionZ)

Just as an example, this file solves this quite nicely

2. spacing the view angles makes sense, but I don't get why I can only specify two view angle pairs. In line 89 you limit this. Why not make it dependent on OptionZ.Periodic?

3. OptionZ.Periodic=true still causes a non-smooth jump when looping the video. Don't know why this is exactly

4. Add export for an animated gif instead of mp4. How to write one can be seen here:

MATLAB Release Compatibility
Created with R2012a
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!