1

I have this code which contains a 3D plot. I run the code in Spyder; I want to know if it is possible to make this plot a rotating one (360 degrees) and save it. Thanks! P.s. Sorry if it is a silly question, but I am a newby in Python.

import matplotlib.pyplot as plt
import numpy as np
from scipy import array
jet = plt.get_cmap('jet')
from matplotlib import animation
fig = plt.figure()
ax = fig.gca(projection='3d')

X = np.linspace(70,40,4)
Y = np.linspace(5,2,4)
X,Y=  np.meshgrid(X, Y)

Z = array ([
        [1223.539555, 1428.075086,1714.479425, 2144.053223],
        [1567.26647,1829.056119,2990.416079,2745.320067],
        [2135.163957,2491.534201, 2990.416079,3738.761638],
        [3257.280827, 3800.655101, 4561.372117, 5702.458776],
        ])

surf = ax.plot_surface(X, Y, Z, rstride = 1, cstride = 1, cmap = jet,linewidth = 0,alpha= 1)
ax.set_zlim3d(0, Z.max())

fig.colorbar(surf, shrink=0.8, aspect=5)
ax.set_xlabel('Axial Length [mm]')
ax.set_ylabel('nbTurns')
ax.set_zlabel('RPM')

plt.show()
Iulia_Vascan
  • 87
  • 3
  • 10

1 Answers1

10

You need to define a function in order to get a specific animation. In your case it is a simple rotation:

def rotate(angle):
    ax.view_init(azim=angle)

Then use the matplotlib animation:

rot_animation = animation.FuncAnimation(fig, rotate, frames=np.arange(0,362,2),interval=100)

This will call the rotate function with the frames argument as angles and with an interval of 100ms, so this will result in a rotation over 360° with a step each 100ms. To save the animation as a gif file:

rot_animation.save('path/rotation.gif', dpi=80, writer='imagemagick')
a.smiet
  • 1,727
  • 3
  • 21
  • 36
  • Hi again, first I want to thank you for your help and answer. I modified my initial code but still I think I have a problem with the saving part. After the run, this error occurs ** renderer._renderer.write_rgba(filename_or_obj) RuntimeError: Error writing to file** – Iulia_Vascan Apr 03 '17 at 10:42
  • This seems to be a common issue (see e.g. http://stackoverflow.com/questions/25140952/matplotlib-save-animation-in-gif-error). Make sure that `imagemagick` is correctly installed, otherwise you could also try to save it in mp4 format, as shown in the link above. – a.smiet Apr 03 '17 at 10:55