4 Python Libraries for 3D Visualization and Graphics

3d Visualization

Visualization is the most important aspect of problem-solving, data analytics, and even emerging technologies like machine learning. Only when you understand something and paint its image mentally will you be able to move forward with the task and make other people understand the problem?

We often deal with problems that require a striking image or visual data to interpret it better or to enhance the experience. Visualization is the process of showing information visually (in the form of an image or a video) to make the data understandable by human brains as they perceive visual data with ease and process the data in visuals within 13 milliseconds. Some researchers also claim that humans process visuals up to 60000 times more than text data. A good visualization tool can make the work easier and transform the data to reach people.

There are many visualization tools that transform the data into visuals depending on the use case. We have bar graphs, pie charts, line graphs, histograms, tree charts, heat maps, and so on, each having its use and characteristics.

We can achieve visualization with Python too! There are a handful of Python libraries that have inbuilt methods to carry out your visualization tasks. These libraries include matplotlib, seaborn, GGplot, and many more to name. These libraries are widely used to visualize data and are the most sought-after libraries by data scientists, data analysts, and machine learning engineers.

Visualization on its own is great. But what if we bring this visualization to life? What if we can interact with the visualization? I’m talking about 3D visualization of data. Is it possible to implement 3D visualization with Python?

3D visualization is more or less like bringing the data to life. 3D typically stands for 3 dimensional and uses three dimensions to plot the data. The visualization tools we discussed earlier(line graphs, histograms, bar graphs) make use of 2 dimensions, and it feels like we are just looking at an image or a picture. But when the third dimension comes into use, that’s when the magic happens, and we feel as if the data has got life.

Python also has a few libraries that support 3D plotting, and in a few minutes, we are going to learn about a few of them one by one.

The most popular 3D visualization library is matplotlib. There are other libraries like Plotly, Mayavi, Pyvista, PyopenGL, and so on. The main difference between matplotlib and the other libraries is that matplotlib generates static 3D visualization, but with other libraries, we can interact with the visual object.

We will see their installations and some examples of how to use them.

3D Visualization with Matplotlib

Matplotlib is one of the most popular libraries of Python. It is used for its various visualization tools like line plots, bar plots, histograms, scatter plots, etc. These are some of the 2D plots this library offers. Matplotlib is built on numpy arrays and can visualize arrays, data frames, etc. Coming to 3D plots, we have different types of surface plots, contours, wireframes,3D histograms, quiver plots, stems, and many more. Although matplotlib mainly creates static 3D objects, we can integrate it with other software and produce interactive 3D plots.

Read this article to get started with matplotlib.

All you need to do is install the library and import it into your environment or script to use it.

To install the library, open your terminal/ command prompt and run the following command.

pip install matplotlib

Now that you have the library installed import it using the following command.

import matplotlib.pyplot as plt

Great! Now depending on your data, you can use any of the plots to use. We will see a simple example of a 3D surface plot and a histogram, so let’s get started!

3D Histogram

A histogram is a graphical representation of user data plotted with ranges. Often confused with bar graphs, a histogram has separated bars, whereas a bar graph has linked bars.

import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
x3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y3 = [1,4,9,16,25,36,49,64,81,100]
z3 = np.zeros(10)
dx = np.ones(10)
dy = np.ones(10)
dz = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
ax.bar3d(x3,y3,z3, dx, dy, dz, zsort='average')
plt.show()

We are importing the matplotlib library and the numpy library. The figure object is created in the third line. The axis object is created using the subplot method with a 3d projection. We define data points x3 (for the X-axis) and y3 (for the Y-axis). The z3 is the third dimension which takes the base of the figure. the dx,dy, and dz give the dimensions of the axes. The bar3d method is used to plot the histogram. The zsort is used to arrange the bars properly.

3d Histogram Matplotlib
3d Histogram Matplotlib

3D Surface Plot

A 3D surface plot is mainly used to represent the relationship between a 3-dimensional object in a 2D space. The x and y axes represent the input data, and the new axis, z, represents the output.

import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator
import numpy as np
fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,
                       linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter('{x:.02f}')
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()

In the first line, we are importing the matplotlib library. Next, we are importing the colormap module from the library. The LinearLocator of the library is used to provide ticks to the plot.

The numpy library is used to generate data. We create the objects figure(fig) and axis(ax) with a 3d projection.

The X and Y values consist of random values between -5 and 5 with a difference of 0.25. These values are used to create a mesh grid. The R variable stores the square root of the X and Y values.

We are creating a surface plot using ax.plot_surface a cool, warm colormap. This plot is stored in surf.

Z is the new axis that stores the sin value of R. A color bar is used to give details about the colormap.

The show method is used to display the plot.

3D Surface Plot Matplotlib
3D Surface Plot Matplotlib

3D Visualization With Plotly

The Plotly is an interactive open-source plotting library that supports over 40 unique chart types covering a wide range of statistical, financial, geographic, scientific, and 3-dimensional use cases. The Plotly library is mainly used in statistics and data science because of its interactive abilities. It is designed for visualization using Python and R and is written in JavaScript. Plotly also supports animations, so if you ever want to animate something, plotly is your go-to!

Refer to this article to learn to plot geographical data on a geographical map.

Here’s how to install Plotly.

pip install plotly
(or)
pip install plotly==5.14.1

Let us see how we can use plotly to create an interactive surface plot.

import plotly.graph_objects as go
import numpy as np
x, y = np.meshgrid(np.linspace(-5, 5, 100), np.linspace(-5, 5, 100))
z = np.sin(np.sqrt(x**2 + y**2))

fig = go.Figure(data=go.Surface(x=x, y=y, z=z, colorscale='Viridis'))  

fig.update_layout(
    title='Surface Plot',
    scene=dict(
        xaxis=dict(title='X'),
        yaxis=dict(title='Y'),
        zaxis=dict(title='Z')
    )
)
fig.show()

The Plotly library’s graph_objects is imported as go. The numpy library is used to generate data.

The x and y variables contain 100 values between -5 and 5 for the x and y coordinates. The z variable consists of the sin of the square root of the x and y values.

A figure object initializes a surface plot with a colormap -Viridis. You can use magma, Jet, RdBu, Hot, and other colormaps. The layout of the figure object is set and given a title. Lastly, the figure is displayed on the screen by the show method.

Here is a demonstration video showing how to interact with the 3D object just by clicking and dragging the mouse to get different views and maximize/minimize the object.

Plotly Interaction

You can try other 3D visualization tools from the plotly documentation linked in the references.

3D Visualization With Mayavi

Mayavi is yet another powerful visualization library that relies on a package called VTK and a user interface tool called PyQt5. So along with installing the mayavi library, we even need to install the dependencies. Mayavi is a powerful visualization tool and provides high-level API to generate 3D visualization for huge volumes of data. It is written in Python and supports visualization of computational grids and scalar, vector, and tensor data. It has a number of contour plots, surface plots, and many more 3D visualization tools. Also supports animation.

Take a look at the installation of mayavi.

pip install mayavi
pip install PyQt5

You don’t need to install the VTK wheel usually, but sometimes especially if you are working with a Jupyter Notebook, you might need to install it.

pip install vtk

Let us see how to create a 3d contour plot using mayavi.

import numpy as np
from mayavi import mlab
x, y, z = np.mgrid[-5:5:50j, -5:5:50j, -5:5:50j]
scalar = np.sin(np.sqrt(x**2 + y**2 + z**2))
fig = mlab.figure()
contour = mlab.contour3d(x, y, z, scalar, colormap='magma')
mlab.xlabel('X')
mlab.ylabel('Y')
mlab.zlabel('Z')
mlab.title('3D Contour Plot')
mlab.show()

We are importing the numpy library and the mlab module from the mayavi library to carry out visualization.

The x,y, and z variables are used to define the coordinates of the grid. It produces 50 values between -5 and 5. The contour we are supposed to create should contain a scalar value, so we are defining a scale that contains the sin of the square root of the x,y, and z values. A figure object is set to create a figure that consists of the contour plot. We are creating a variable called contour that stores the contour plot created by the contour3d method. The labels and title of the plot are set in the next four lines.

Finally, we display the figure using the show method.

This code takes a few minutes to run as the mayavi library is a powerful library, and it might take a few mins to process the code. Also, if you use Google Colaboratory, this code might take up all the processing units. It is advised to use Jupyter Notebook. After the successful run, you will see a scene box on your taskbar. This scene box has a few buttons to view and interact with the 3D object.

Interaction with Mayavi Contour Plot

3D Visualization with PyVista

The pyvista is another module built on the visualization tool kit(VTK). It mainly provides 3D mesh plots along with other 3D plots like point clouds, maps, spline, and volumetric data. It also allows boolean operation on meshes.

You can install the pyvista library using the following command.

pip install pyvista

We are going to see how to plot a spline using pyvista. A spline is a polynomial curve whose movement is determined by a set of control points. It is mainly used in computer-aided design(CAD), numerical and statistical analysis.

import numpy as np
import pyvista  as pv
theta = np.linspace(-10 * np.pi, 10 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
points = np.column_stack((x, y, z))
spline = pv.Spline(points, 500).tube(radius=0.1)
spline.plot(scalars='arc_length', show_scalar_bar=True)

In the first two lines, we are importing the numpy library and the pyvista library. We are initializing a theta variable to store 100 values between -10pi and 10pi. The z variable is used to store 100 values between -2 and 2. The r is the dependent variable which stores the value of the square of z, adding 1. The x variable stores the value of the product of r and sin of theta, whereas the y variable stores the cos of it. The points variable stores the x,y, and z variables as coordinates of the curve in the form of a stack. The spline is created with a tube radius of 0.1 and has 500 values to interpolate. The spline.plot is used to plot the spline curve along with its scalar bar and the arc_length is used to give color to the curve based on its arc.

Like mayavi, pyvista also provides a set of buttons to interact with the 3D plot. Here is a demonstration of it.

Interaction with Pyvista Spline

The examples provided in this tutorial are just a few of the many things you can do with these libraries discussed.Please follow the documentation examples to explore the tools and create wonders.

Conclusion

We have reached the end of this tutorial. I hope this comprehensive guide to 3D visualization using Python was useful. The four libraries we discussed here are matplotlib, Plottly, Mayavi, and PyVista.

Matplotlib is basically deployed to do basic plotting. So if you want a static but informative plot, matplotlib is your bestie.

Plotly is a great 3D visualization tool to start with. It offers many 3D plots and even geographical maps to plot geographical or geospatial data.

Coming to mayavi and PyVista, we can interact with the plots with the help of scene boxes, toggles, buttons, and many more. You can choose these libraries if you want to go with animation or a movie-like visualization.

You can, of course, explore more tools of these libraries by going through the documentation of these libraries provided below.

References

You can find more about the Numpy Library here.

Matplotlib 3D.

Plotly.

Mayavi.

PyVista.