Are you looking to plot interactive 3d plots in Python? Stay with us and we will explore various methods to have interactive 3d plots in Python.
3D plots are used to plot data points on three axes in an attempt to show the relationship between three variables. Each row in the data table is represented by a marker whose position depends on its values in the columns set on the X, Y, and Z axes. In this article, we will discuss various kinds of 3D plots and visualize them using plotly and matplotlib modules
You might be interested in visualizing data using heatmaps and hexagons on a google map.
3D plots in python using matplotlib
Matplotlib was initially designed with only two-dimensional plotting, but with the updates, they include 3D plots as well. Before going to the implementation part, make sure that you have installed the following required modules.
Let us now import the required modules.
# importing the matplotlib module import matplotlib.pyplot as plt # importing 3d ploting from mpl_toolkits.mplot3d import Axes3D
Once you import the required modules, we can then move to the practical and visualization part. You can access the source code and all the datasets from my GitHub account.
Plotting a single point in a 3D plot using matplotlib
We will start the 3D visualization from the very beginning. First, we will just create the 3D figure and axes.
# fixing the size of the plot fig = plt.figure(figsize=(9,9)) # creating 3D space ax = fig.add_subplot(111, projection='3d')
As you can see, we have successfully created a 3D space. Now, let us plot a point in this space.
# fixing the size fig = plt.figure(figsize=(9,9)) # plotting the 3d space ax = fig.add_subplot(111, projection='3d') # plotting the points ax.scatter(5,6,7) plt.show()
As you can see, we have successfully plotted the point in the 3D space.
3D line plot using matplotlib
Now, we will create a function for a continuous line and then plot it on the 3D plot using matplotlib. Let us first create a random function for the line.
# importing the module import numpy as np # creating x axis data x = np.linspace(-4*np.pi,4*np.pi,100) # creating y axis data y = np.linspace(-4*np.pi,4*np.pi,100) # creating z axis data z = x**5 + y**7
Now, let us plot the line that we just created in a 3D space.
# fixing the size fig = plt.figure(figsize=(9,9)) # plotting the 3d space ax = fig.add_subplot(111, projection='3d') # plotting the points ax.plot(x,y,z) plt.show()
As you can see, we have successfully plotted the line in the 3D space.
3D contour plot using matplotlib
A contour plot is a graphical technique for representing a 3-dimensional surface by plotting constant z slices, called contours, in a 2-dimensional format. We will first create a function that defines the axes and then will plot in the 3D space.
# function to return a function def f(x, y): return np.sin(np.sqrt(x + y ** 3)) # creating x and y x = np.linspace(-50, 10, 50) y = np.linspace(-50, 10, 50) # using meshgrid function for x and y X, Y = np.meshgrid(x, y) # calling the function Z = f(X, Y)
As you can see, we have created a random function for the demonstration purpose. Let us now visualize this function using a contour plot.
# plotting the graph fig = plt.figure(figsize=(8, 8)) # plotting conter plot ax = plt.axes(projection='3d') ax.contour3D(Y, Z, X, 50) ax.set_title('3-D contour plot') #showing 3D plots in python plt.show()
As you can see, we have successfully plotted the contour plot of the dataset. When you are plotting the contour plot of your own dataset, make sure that the z-axis contains the dataset in 2d array form.
3d wireframe plot using matplotlib
Wireframe plot takes a grid of values and projects it onto the specified three-dimensional surface, and can make the resulting three-dimensional forms quite easy to visualize. Let us plot the same function using a wireframe plot.
# fixing the size fig = plt.figure(figsize=(8,8)) # creating 3d space ax = plt.axes(projection='3d') #wirefram plot ax.plot_wireframe(Y, Z, X, color='purple') ax.set_title('Wireframe plot') #showing 3D plots in python plt.show()
As you can see, we have successfully plotted the wireframe plot of the given function.
3D surface plot using maplotlib
A surface plot is a three-dimensional wireframe graph that is useful for establishing desirable response values and operating conditions. A surface plot contains the following elements: Predictors on the x- and y-axes. A continuous surface that represents the fitted response values on the z-axis. Now, we will plot the same function on a surface plot as well.
# size of the 3-d plot fig = plt.figure( figsize=(8, 8)) ax = plt.axes(projection='3d') # surface plot ax.plot_surface(Y, Z, X, color='purple') ax.set_title('Surface plot') #showing 3D plots in python plt.show()
As you can see, we have plotted the surface of the same function.
3D plots in python using plotly
Plotly is a free and open-source graphing library for Python. It provides online graphing, analytics, and statistics tools for individuals and collaboration, as well as scientific graphing libraries for Python, R, MATLAB, Perl, Julia, Arduino, and REST. Before going to the implementation part, make sure that you have installed the Plotly module on your system.
The good thing about plotly plots is that they are more interactive.
3D axes in Plotly
Before going to visualization of the different data points in various 3D plots. Let us first learn how to stack the 3D axes and the plane. For the demonstration purpose, we will create a random dataset for the x, y, and z axes and then will learn how to color and label them.
# seleting the randomness np.random.seed(1) N = 30 # creating the figure with random dataset fig = go.Figure(data=[go.Mesh3d(x=(3*np.random.randn(N)), y=(5*np.random.randn(N)), z=(4*np.random.randn(N)), opacity=0.6, color='#9560FD' )]) # fixing the labeing ( axes) fig.update_layout( scene = dict( xaxis = dict(nticks=4, range=[-10,10],), yaxis = dict(nticks=4, range=[-5,10],) zaxis = dict(nticks=4, range=[-10,10],),), width=800, margin=dict(r=20, l=10, b=10, t=10)) # 3D plots in python fig.show()
As you can see, we have created a simple 3D plot. Now let us learn how to plot two different datasets on the same 3D plot. We will use the
trace() function to plot multiple datasets on the same graph.
fig = go.Figure() fig.add_trace(go.Mesh3d(x=(6*np.random.randn(N)), y=(5*np.random.randn(N)), z=(0*np.random.randn(N)), opacity=0.5, color='red' )) fig.add_trace(go.Mesh3d(x=(3*np.random.randn(N)), y=(5*np.random.randn(N)), z=(4*np.random.randn(N)), opacity=0.6, color='#9560FD' )) fig.update_layout(scene = dict( xaxis_title='X AXIS', yaxis_title='Y AXIS', zaxis_title='Z AXIS'), width=700, margin=dict(r=20, b=10, l=10, t=10)) # 3D plots in python fig.show()
As you can see, this time also had added labeling to the plot as well.
3D line plots using plotly
Now, we will plot 3D lines plots using the plotly module. First, we will create sin and cosine functions and will plot them in 3D.
# importing the module import math # creating the variables z = np.arange(0, math.pi*2, 0.1) x = np.sin(z) y= np.cos(z)
Now, let us visualize the above lines in 3D plots.
# importing the plotly module import plotly.express as px # fixing the axis and 3D plots in python fig = px.line_3d( x=z, y=y, z=x) fig.show()
As you can see the graph is interactive as well. Now, let us plot the 3D line but this time we will use the build in the dataset from the plotly module itself.
# importing the dataset about df = px.data.gapminder().query("continent=='Asia'") # plotting 3D plots in python fig = px.line_3d(df, x="gdpPercap", y="pop", z="year", color='country') fig.show()
As you can see, we have plotted the line plots for different countries in Asia.
3D volume plots using plotly
A volume plot is a plot with go that shows many partially transparent isosurfaces for rendering the volume. Volume results in a depth effect and generates better volume rendering. Let us first create a sample dataset and visualize it using 3D volume plots
# creating a random dataset X, Y, Z = np.mgrid[-4:8:30j, -3:8:30j, -1:8:30j] values = np.sin(X*Y*Z) / (X*Y*Z)
Now let us plot the volume plot. The go.Figure() takes a lot of optional parameters to make the graph more interactive and beautiful. Here, we will use some of them.
# plotting the volume plot with optional parameters fig = go.Figure(data=go.Volume( x=X.flatten(), y=Y.flatten(), z=Z.flatten(), value=values.flatten(), isomin=0.1, isomax=0.8, opacity=0.3, surface_count=17, )) #3D plots in python fig.show()
It is like heatmap, where different colors show the intensity of the data points.
3D scatter plots using plotly
A scatter plot is a set of points plotted on horizontal and vertical axes. Scatter plots are important in statistics because they can show the extent of correlation, if any, between the values of observed quantities. Now, we will use a real dataset and plot in a 3D plot. Let us first import the dataset.
# importing the dataset data = pd.read_csv('house.csv') # heading data.head()
Now, let us plot the latitude, longitude, and price on a 3D scattered plot.
# plotting 3d plot fig = px.scatter_3d(data, x='latitude', y='longitude', z='price', color='price') #3D plots in python fig.show()
As you can see we have successfully plotted a scattered plots and different colors represent the prices.
3D bubble plots using plotly
An extension of a scatterplot, a bubble chart is commonly used to visualize relationships between three or more numeric variables. Each bubble in a chart represents a single data point. We will not visualize the bubble plot in 3D space. Let us first import the dataset that we gonna visualize.
# importing dataset data = pd.read_csv('data.csv') # heading data.head()
Let us now use the bubble plot to visualize the above dataset.
# plotting the graph fig = go.Figure(data=go.Scatter3d( x=data['year'], y=data['continent'], z=data['pop'], text=data['country'], mode='markers', marker=dict( sizemode='diameter', sizeref=750, size=data['gdpPercap'], color = data['lifeExp'], colorscale = 'Viridis', colorbar_title = 'Life<br>Expectancy', line_color='purple' ) )) #3D plots in python fig.update_layout(height=900, width=800,) fig.show()
As you can see, we have visualized the data using the bubble plot.
3D plots in python are plots that show the data in three different directions/coordinates. In this tutorial, we learned various techniques to visualize data in 3D plots using matplotlib and plotly modules.
7 thoughts on “How to visualize 3D plots in python using Plotly and Matplotlib”