#342 Animation on 3D plot

It is possible to create a 3D object with python. See the dedicated section. Once this is done, we can make evolute the angle of view (‘camera position’) and use each image to make an animation. Once more, the image are transformed to a GIF using Image magic.


# library
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

# Get the data (csv file is hosted on the web)
url = 'https://python-graph-gallery.com/wp-content/uploads/volcano.csv'
data = pd.read_csv(url)

# Transform it to a long format
df=data.unstack().reset_index()
df.columns=["X","Y","Z"]

# And transform the old column name in something numeric
df['X']=pd.Categorical(df['X'])
df['X']=df['X'].cat.codes

# We are going to do 20 plots, for 20 different angles
for angle in range(70,210,2):

# Make the plot
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_trisurf(df['Y'], df['X'], df['Z'], cmap=plt.cm.viridis, linewidth=0.2)

# Set the angle of the camera
ax.view_init(30,angle)

# Save it
filename='PNG/ANIMATION/Volcano_step'+str(angle)+'.png'
plt.savefig(filename, dpi=96)
plt.gca()

Then use image magic to transform all the png files into an GIF file.


# Then use image magick (this is bash, not python)
convert -delay 50 Volcano*.png animated_volcano.gif

  • Sponsors

  • 3 comments

    • Hello, I use the Spyder to run ImagicMaker but the Image not animate, so where and how to install ImageMagic for the program recognize the command line
      Can you help me please

      Reply
      • Hi Jose,

        The ImageMagick software must be installed separately. Everything is explained here. If you use Mac, it is really handy to use homebrew to make the installation: brew install imagemagick

        Then, the last line of code must be run in a bash terminal, not in the python console since image magic is NOT a python library!

        Hope it helps

        Reply
        • I have the ImageMake-windouws.zip download and unzip. But following your steps when I launch Visual Studio and choose Open Project and go to the folder all files appear empty. And in the MS-DOS prompt not have the statement unzip. So I go to the folder and choose Visual Studio to Open. That is opened in Visual Studio but not appear the button Build. Can you help me on this issue?
          Thank you very much
          José da Conceição

          Reply

    Leave a Reply

    Your email address will not be published.