5 Best Ways to Create Three-Dimensional Scatter Plots Using Matplotlib in Python

Rate this post

πŸ’‘ Problem Formulation: You have a set of data points in three-dimensional space and wish to visualize them. Specifically, you’re looking to create a three-dimensional scatter plot to gain insights into the distribution, clusters, or outliers present in the data. The input is a set of (x, y, z) coordinates, and the desired output is a graphical scatter plot that can be rotated and examined from different angles.

Method 1: Using Axes3D from mpl_toolkits.mplot3d

This method involves importing the Axes3D class from the mpl_toolkits.mplot3d module. First, create a 3D subplot using the subplot method with the projection set to ‘3d’. Then use the scatter method on the created axis to plot your 3D data.

Here’s an example:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = [1, 2, 3, 4, 5]
y = [5, 6, 2, 3, 13]
z = [2, 3, 3, 3, 5]

ax.scatter(x, y, z, c='r', marker='o')

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()

The output is a window displaying a 3D scatter plot with red circular markers at each given (x, y, z) data point.

The code snippet above creates a Matplotlib figure, adds a 3D subplot to it, and then plots the data points in three-dimensional space. The ‘c’ argument specifies the color of the markers, while the ‘marker’ argument defines the style of the markers. The x, y, and z axis labels are set to provide context to the plot.

Method 2: Using plotly

Although not part of Matplotlib, plotly is a powerful graphing library that allows for interactive 3D scatter plots. Simply install the plotly package and use the Scatter3d component to create a 3D scatter plot. This method provides interactivity out of the box.

Here’s an example:

import plotly.graph_objs as go
import plotly.offline as pyo

trace = go.Scatter3d(
    x=[1, 2, 3, 4, 5],
    y=[5, 6, 2, 3, 13],
    z=[2, 3, 3, 3, 5],
    mode='markers',
    marker=dict(size=10, color='rgba(255, 0, 0, .9)', symbol='circle')
)

data = [trace]
layout = go.Layout(title='3D Scatter plot')

fig = go.Figure(data=data, layout=layout)
pyo.plot(fig)

The output is an interactive 3D scatter plot rendered in a web browser, allowing you to rotate and zoom in/out of the plot.

The code creates a Scatter3d trace with x, y, and z data, and customizes the marker appearance. After defining the layout with a title, it constructs a Figure object which is then plotted in a browser window. The interactivity of the plot facilitates better data exploration.

Method 3: Using seaborn

Seaborn is a statistical data visualization library based on Matplotlib that provides a high-level interface for drawing attractive and informative statistical graphics. For a 3D scatter plot, you can combine Seaborn for styling with Matplotlib for the plotting.

Here’s an example:

import matplotlib.pyplot as plt
import seaborn as sns
from mpl_toolkits.mplot3d import Axes3D

sns.set(style='whitegrid')  # Styling from seaborn
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

x = [1, 2, 3, 4, 5]
y = [5, 6, 2, 3, 13]
z = [2, 3, 3, 3, 5]

ax.scatter(x, y, z)
plt.show()

The output is a Matplotlib 3D scatter plot but with the attractive styling of Seaborn applied.

This code adds a Seaborn-style white grid background to a Matplotlib 3D scatter plot. The rest of the plotting process remains the same as in Method 1. The result combines the ease of Matplotlib’s 3D plotting with the aesthetics of Seaborn.

Method 4: Using mplot3d with a Color Map

When using Matplotlib’s mplot3d toolkit, you can add more dimensionality by utilizing a color map to reflect the value of an additional variable, essentially encoding four variables into the plot.

Here’s an example:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = np.random.standard_normal(100)
y = np.random.standard_normal(100)
z = np.random.standard_normal(100)
c = np.arange(100)  # An additional variable for color mapping

img = ax.scatter(x, y, z, c=c, cmap=plt.hot())
fig.colorbar(img)
plt.show()

The result is a color-mapped 3D scatter plot where the colors reflect the values of an additional variable and a color bar to interpret this dimension.

The code generates random data points and an additional array c which acts as the color map input. The color map (cmap) is specified to use the ‘hot’ color scheme. We add a color bar to the plot for reference to the variable represented by the color.

Bonus One-Liner Method 5: Customizing Marker Size

Enrich your 3D scatter plot by customizing the marker size based on an additional data variable with a one-liner code enhancement to the Axes3D.scatter() method.

Here’s an example:

ax.scatter(x, y, z, s=np.abs(z)*100)

The output will vary the marker size proportionally to the absolute value of the z-coordinate, adding another layer of information to the scatter plot.

This one-liner modifies the size of the scatter plot markers (s) to be proportional to the absolute value of the z data, thereby giving visual emphasis to certain data points over others within the same plot.

Summary/Discussion

  • Method 1: Axes3D from mpl_toolkits.mplot3d. This method integrates seamlessly within the Matplotlib environment and offers simplicity and compatibility with Matplotlib’s plotting conventions. However, it may lack the interactivity of more advanced visualization tools.
  • Method 2: Using plotly. Plotly’s chief strength is its interactive plots that can be easily shared as HTML. This makes it superb for exploratory data analysis. Its downside is the necessity to learn a different syntax and the potential overkill for quick and simple plots.
  • Method 3: Using seaborn. Seaborn excels in elevating the aesthetic of Matplotlib plots with minimal code adjustments. Although it does not provide direct methods for 3D plotting, its integration with Matplotlib can embellish 3D plots with predefined styles. It is limited by Matplotlib’s capabilities for 3D plotting.
  • Method 4: Using mplot3d with a Color Map. The addition of a color map introduces another layer of information, making the plot more informative. The technique may become complicated if the reader is not familiar with color mapping concepts.
  • Bonus Method 5: Customizing Marker Size. Customizing marker size is an easy way to introduce an additional data dimension in a visually intuitive manner. However, care must be taken to ensure that the resulting plot does not become cluttered and hard to interpret due to overly large or overlapping markers.