Guide To Mayavi: A Python Tool For Visualizing and Plotting 2D/3D Scientific Data

Mayavi

Mayavi is a cross-platform library and application for 2D and 3D plotting and interactive visualization of scientific data using Python. It leverages the power of Visualization Toolkit (VTK) without requiring the users to have its prior knowledge. It acts as a clean and lucid Python interface that enables plotting complex figures with a few code lines; some of them can even be plotted using one-liners. Besides, it also provides an object-oriented interface for the same purposes.

Highlighting Features of Mayavi

  • It enables visualization of scalar, vector and tensor data in 2D and 3D.
  • It can act as an alteranate to Matlab or Pylab for plotting and visualizing 3D data using NumPy via the mlab module.
  • It can also be used as an interactive application. Read about the usage of Mayavi as an application here.
  • It provides options for various image formats for saving the rendered visualizations.
  • It makes use of the Enthought Tool Suite (ETS).
  • Earlier version of Mayavi was Mayavi1 while its latest version is Mayavi2 which has been designed keeping extensibility and scriptability in mind. Because of its cleaner MVC design, it is also easier to script Mayavi2 than Mayavi1.

How Mayavi works?

Similar to VTK, Mayavi makes use of a pipeline architecture. Data in Mayavi is stored in a ‘data source’, which is nothing but a data file or a data object describing the data to be used for visualization and plotting. This data can be stored in a VTK-supported file format. Alternatively, it can be generated as sequences like NumPy arrays using simple scripting API such as mlab. It is then processed using Filters and can be visualized using various Modules for visualization. Since there can be different ways of visualizing some given data, ‘data source’ and ‘modules’ have been kept as separate sections of the library to visualize different entities from various perspectives by applying different modules to a common data source. The area where visualization is performed in a Mayavi application is termed as a ‘scene’.

Practical implementation

Here’s a demonstration of plotting various 3D figures using easy-to-use built-in functions provided by Mayavi library. The following code implementation referenced the official examples of Mayavi and verified in Google Colab with  Python 3.7.10 and Mayavi 4.7.2 versions. Step-wise explanation of the code is as follows:

THE BELAMY

Sign up for your weekly dose of what's up in emerging technology.
  1. Install required dependencies
 !apt-get install vtk6
 !apt-get install python-vtk
 !pip install numpy vtk pyqt5
 ! pip install scipy jupyter ipywidgets ipyevents 
  1. Install Mayavi library

!pip install mayavi

  1. Setup environment for plotting interactive plots 
 !apt-get install -qq xvfb
 import os     #For interacting with the Operating System
 os.system('/usr/bin/Xvfb :99 -screen 0 1024x768x24 &')
 #Define environmental variable using os.environ object
 os.environ['DISPLAY'] = ':99'
 import panel as pn
 pn.extension('vtk') #for interacting with complex 3D geometry 
  1. Import NumPy and Mayavi’s mlab module
 import numpy as np
 from mayavi import mlab 
  1. IMP NOTE: For visualizing Mayavi visualization in Jupyter notebooks, it is required to call init_notebook() method which configures Mayavi objects to be rendered on the notebook. Visit this page of the official documentation, which suggests the way of dealing with Mayavi using Jupyter notebook.

mlab.init_notebook()

On successful execution of the above line of code, we get the following output:

Notebook initialized with ipy backend.

  1. Plot glyphs like points at pre-defined positions using test_points3d() method.

mlab.test_points3d()

Output:

Mayavi op1

  IMP NOTE: After every plot, remember to clear the current figure using mayavi.mlam.clf() method, otherwise the next plot will get overlapped with the current one.

  mlab.clf()

  1. Draw lines joining successive points using plot3d() method

mlab.test_plot3d()

Output:

Mayavi op2
 #Clear the current figure
 mlab.clf() 
  1. Plot arrows showing direction of vectors at specified position using test_quiver3d()

mlab.test_quiver3d()

Output:

Mayavi op3
 #Clear the current figure
 mlab.clf() 
  1. Plot a surface with regularly-spaced elevation using test_surf()

mlab.test_surf()

Output:

Mayavi op4
 #Clear the current figure
 mlab.clf() 
  1. Plot a surface from a mesh formed by joining vertices of a triangle using test_triangular_mesh()

mlab.test_triangular_mesh()

Output:

 #Clear the current figure
 mlab.clf() 
  1. Plot isosurface for 3D data using test_contour3d() method

mlab.test_contour3d()

Output:

 #Clear the current figure
 mlab.clf() 
  1.  Draw histogram-like plots in 3D using test_barchart() method

mlab.test_barchart()

Output:

 #Clear the current figure
 mlab.clf() 
  1. Plot flow of a vector field using test_flow() method

mlab.test_flow()

 #Clear the current figure
 mlab.clf() 
  1. Plot a surface from grid-spaced data using test_mesh()

mlab.test_mesh()

Output:

 #Clear the current figure
 mlab.clf() 
  1. Plot an attractive mesh using fancy_mesh()

mlab.test_fancy_mesh()

Output:

 #Clear the current figure
 mlab.clf() 
  1. Plot a spherical mesh

mlab.test_mesh_sphere()

Output:

 #Clear the current figure
 mlab.clf() 

For more attractive spherical mesh,

mlab.test_mesh_mask_custom_colors()

Output:

 #Clear the current figure
 mlab.clf() 

NOTE: As mentioned in step (6), if mlab.clf() is used to clear current figure, successive plots will get overlapped. This technique can be used to mix two or more 3D plots as in the following step.

  1. Plots of step (7) and (10) can be combined by not specifying mlab.clf() after plotting the triangular mesh as follows:
 mlab.test_triangular_mesh()
 mlab.test_plot3d() 

Output:

 #Clear the current figure
 mlab.clf() 
  1. Plot a z-warped surface representing Julia set
 #Create a muti-dimensional grid using numpy.ogrid()
 x, y = np.ogrid[-1.5:0.5:500j, -1:1:500j]
 #Calculate z-dimension
 z = x + 1j * y
 #Initialize an array representing Julia set with zeros
 julia = np.zeros(z.shape)
 #Compute Julia set
 for i in range(50):
     z = z ** 2 - 0.70176 - 0.3842j
     julia += 1 / float(2 + i) * (z * np.conj(z) > 4)
 # Display the Julia set using surf() method
 mlab.figure(size=(400, 300))
 mlab.surf(julia, colormap='gist_earth', warp_scale='auto', vmax=1.5) 

Output:

IMP NOTE: While executing the Google colab code having multiple Mayavi plots, it is recommended to run the cells manually one-by-one. Allowing the cells to get executed independently by selecting ‘Run all’ or ‘Restart and run all’ option may sometimes result in output plots that do not match the input code since a cell may get executed before the previous figure gets cleared.

References

For an in-depth understanding of the Mayavi library and tutorials for more examples, refer to the following sources:

More Great AIM Stories

Nikita Shiledarbaxi
A zealous learner aspiring to advance in the domain of AI/ML. Eager to grasp emerging techniques to get insights from data and hence explore realistic Data Science applications as well.

Our Upcoming Events

Conference, in-person (Bangalore)
Machine Learning Developers Summit (MLDS) 2023
19-20th Jan, 2023

Conference, in-person (Bangalore)
Rising 2023 | Women in Tech Conference
16-17th Mar, 2023

Conference, in-person (Bangalore)
Data Engineering Summit (DES) 2023
27-28th Apr, 2023

Conference, in-person (Bangalore)
MachineCon 2023
23rd Jun, 2023

Conference, in-person (Bangalore)
Cypher 2023
20-22nd Sep, 2023

3 Ways to Join our Community

Whatsapp group

Discover special offers, top stories, upcoming events, and more.

Discord Server

Stay Connected with a larger ecosystem of data science and ML Professionals

Subscribe to our newsletter

Get the latest updates from AIM