The Wayback Machine - https://web.archive.org/web/20240725062232/https://www.geeksforgeeks.org/exploring-3d-data-visualization-with-mayavi-in-python/
Open In App

Exploring 3D Data Visualization with Mayavi in Python

Last Updated : 22 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Mayavi is an interactive 3D plotting library that can be used to visualize complex spatial datasets. Although matplotlib can also be used for simple 3D plotting, Mayavi uses a more complex engine (VTK), making Mayavi more suitable for displaying large and complex data. The Mayavi library is like a magic tool that helps us do lots of cool things in a computer program, like creating 3d plots and graphs. We can use it by adding it to our program in Python.

In this article, we will understand and explore the Mayavi library for 3D visualization.

Exploring Mayavi Module

In the Mayavi module, we can easily see and understand scientific data with the help of different tools. But MayaVi is special because it has other cool features that make it stand out from other similar modules. Let’s talk about these features now:

  • The Mayavi module is a helpful tool for making graphs and pictures of scientific information. It can also be used with the Mayavi extension for even more features.
  • The Mayavi module can help you open and read different types of files, like PLOT3D and VTK, which is really useful.
  • The Mayavi module can easily be used in any Operating System (OS).
  • Mayavi is like a special tool that lets you look at and change things in a pipeline of objects.
  • With the Mayavi module, we can bring in basic 3D pictures and VRML scenes.

Installing Mayavi for 3D Data Visualization

We can use pip to install the Mayavi library in our notebook. If you are installing the library in your local system, you can follow these steps:

Install PyQt5:

pip install PyQt5

Then, you can install Mayavi by running the following commands in your terminal or command prompt:

pip install mayavi

Alternatively, you can install Mayavi from source by downloading the source code from the Mayavi website and then running:

python setup.py install

This will install Mayavi along with its dependencies.

Running the Application

To check if the installation is complete and to run the application call this command in the terminal (MacOS):

mayavi2

For some other platforms like win34 double click mayavi2.exe or mayavi2.py file in the scripts folder which will be inside PythonXY\mayavi folder.

Screenshot-2024-05-01-165917

If the installation is completed without any error, this window will open:

Screenshot-2024-05-01-170704

Utilizing the Application for 3D Data Visualization

Now let’s see how to use the application with few examples. Let’s first create a random 3d points using numpy and mlab.points3d() function from mayavi library.

  • In this program, first we will import necessary libraries which are numpy and mlab from mayavi.
  • Then we will assign random numbers to variables named x, y, z, and value using np.random.random() function.
  • Finally, we will use points3d() function and pass the above variables are parameter to generate the 3d plot.
Python
from mayavi import mlab
import numpy as np

x, y, z, value = np.random.random((4, 40))
mlab.points3d(x, y, z, value)

Save this code with .py extension in your system. Now in the mayavi application click on file/Run Python Script, then select the saved python file.

Screenshot-2024-05-01-171316Once you open the python script you will see the output.

Output:

1. 3D Lines Visualization with Mayavi

Now let’s plot a 3d line visualization using plot3d() function. We can provide the thickness of the line and the colour we want as parameter to the function. Here’s how to do it:

  • First we will import the necessary libraries which are numpy and mlab from mayavi.
  • Then we will create a variable t in which we will use numpy’s linspace function to generate evely spaced numbers that are spread out in a certain range.
  • Finally we will use plot3d() function, in which the x coordinate will be np.sin(t), y coordinate will be np.cos(t), and z coordinate will be 0.01*t. Then the last parameter will be ‘t‘ which is used to specify the scalar values associated with each point.
Python
from mayavi import mlab
import numpy as np

t = np.linspace(0, 20, 200)
mlab.plot3d(np.sin(t), np.cos(t), 0.1*t, t)

Output:

Save the above code in a new filename.py file and load into the mayavi2 application in the same way as before.

2. 3D Arbitrary Regular Mesh

Now let’s create a arbitrary regular mesh defined by x, y, z positions of node points. This surface is defined by points connected to form triangles or polygons. We can use mlab.mesh() function to create this plot.

As usual, first we will import the numpy and mayavi libraries.

  • Now we will use mgrid() function to create a mesh grid of spherical coordinates.
  • Then we will do spherical-to-Cartesian coordinate transformations.
  • Finally we will use mesh() function and pass the x, y, z parameters into this function to create the arbitrary regular mesh.
Python
from mayavi import mlab
import numpy as np

phi, theta = np.mgrid[0:np.pi:11j, 0:2*np.pi:11j]
x = np.sin(phi) * np.cos(theta)
y = np.sin(phi) * np.sin(theta)
z = np.cos(phi)
mlab.mesh(x, y, z)
mlab.mesh(x, y, z, representation='wireframe', color=(0, 0, 0))

Output:

3. 3D Elevation Surface Using Mayavi

An elevation surface is like a bumpy map that shows how high or low things are in a certain area. It helps us see the shape of the land and how steep or flat it is. We use elevation surfaces to study things like mountains, rivers, and other natural features. It helps us see patterns and understand how things are arranged in space.

  • After importing the necessary libraries, we will use mgrid() function to generate a grid of x and y values. This is similar to the plt.clf() function of matplotlib.
  • Then we will calculate distance from the origin to each point and assign it to the variable r.
  • Then we will calculate z values for each point using the distance calculated in the precious step.
  • Finally we will use surf() function and pass the parameter z to create the elevation surface plot.
Python
from mayavi import mlab
import numpy as np

x, y = np.mgrid[-10:10:100j, -10:10:100j]
r = np.sqrt(x**2 + y**2)
z = np.sin(r)/r
mlab.surf(z, warp_scale='auto')

Output:

4. Volumetric Data with Mayavi

Volumetric data refers to a type of data that represents information distributed throughout a three-dimensional space, often within a grid or voxel structure. This data typically represents properties such as density, temperature, pressure, or other scalar or vector quantities within a volumetric region and we can see what’s inside by dividing it into lots of little squares and checking what’s in each square.

  • Just like above examples, we will first import the necessary libraries then we will use mgrid() function to generate spatial coordinates of the points in the grid.
  • Then we will compute the scalar values of each point in grid and assign it to the variable values.
  • Finally we will use contoured() function to create the volumetric plot.
Python
from mayavi import mlab
import numpy as np

x, y, z = np.mgrid[-5:5:64j, -5:5:64j, -5:5:64j]
values = x*x*0.5 + y*y + z*z*2.0
mlab.contour3d(values)

Output:

Conclusion

Mayavi is a really helpful tool that lets people look at and understand complicated data in a 3D way. It’s easy to use and has lots of cool features, making it great for scientists and developers. You can do all sorts of things with it, like making basic 3D graphs or more advanced visualizations. It works with Python and can be used on different types of computers, so lots of people can use it to help them study and analyze data in a more visual way.



Similar Reads

Exploring Categorical Data
Categorical Variable/Data (or Nominal variable): Such variables take on a fixed and limited number of possible values. For example – grades, gender, blood group type, etc. Also, in the case of categorical variables, the logical order is not the same as categorical data e.g. “one”, “two”, “three”. But the sorting of these variables uses logical orde
2 min read
Exploring Basics of Informatica Data Profiling
Data Profiling is an important step in data quality assurance. By profiling your data, you can identify any data quality issues that need to be addressed. This can help to ensure that your data is accurate, complete, and consistent, which is essential for effective data analysis and decision-making. It is the process of gathering statistics and dat
8 min read
Exploring Data Distribution | Set 1
Whenever we work in data science and machine learning, our approach of handling the data and finding something useful out of it is based on the distribution of the data. Distribution means that how data can be present in different possible ways, the percentage of specific data, identifying the outliers. So, data distribution is the way of using gra
2 min read
Exploring Data Distribution | Set 2
Prerequisite: Exploring Data Distribution | Set 1Terms related to Exploration of Data Distribution -> Boxplot -> Frequency Table -> Histogram -> Density Plot Loading Libraries C/C++ Code import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt Loading Data C/C++ Code data = pd.read_csv("../data/s
2 min read
Exploring Geospatial Data with Pydeck: Advanced Visualizations
Geospatial data visualization is the key to unlocking insights from location-based information. Pydeck is an advanced Python library for building interactive geospatial data visualizations. It leverages [deck.gl](http://deck.gl/), a framework for exploring large datasets, to enable users to visualize complex patterns in geospatial data with customi
9 min read
Exploring Correlation in Python
This article aims to give a better understanding of a very important technique of multivariate exploration. A correlation Matrix is basically a covariance matrix. Also known as the auto-covariance matrix, dispersion matrix, variance matrix, or variance-covariance matrix. It is a matrix in which the i-j position defines the correlation between the i
4 min read
Why Data Visualization Matters in Data Analytics?
What if you wanted to know the number of movies produced in the world per year in different countries? You could always read this data in the form of a black and white text written on multiple pages. Or you could have a colorful bar chart that would immediately tell you which countries are producing more movies and if the total movies per year are
7 min read
Difference Between Data Mining and Data Visualization
Data mining: Data mining is the method of analyzing expansive sums of data in an exertion to discover relationships, designs, and insights. These designs, concurring to Witten and Eibemust be "meaningful in that they lead to a few advantages, more often than not a financial advantage." Data in data mining is additionally ordinarily quantitative par
2 min read
Difference Between Data Visualization and Data Analytics
Data Visualization: Data visualization is the graphical representation of information and data in a pictorial or graphical format(Example: charts, graphs, and maps). Data visualization tools provide an accessible way to see and understand trends, patterns in data and outliers. Data visualization tools and technologies are essential to analyze massi
3 min read
Difference Between Data Science and Data Visualization
Data Science: Data science is study of data. It involves developing methods of recording, storing, and analyzing data to extract useful information. The goal of data science is to gain knowledge from any type of data both structured and unstructured. Data science is a term for set of fields that are focused on mining big data sets and discovering t
2 min read
Practice Tags :
three90RightbarBannerImg