python logo

3d scatter plot python


Python hosting: Host, run, and code Python in the cloud!

Matplotlib is a powerful library in Python for data visualization. In this tutorial, you’ll learn how to create a 3D scatter plot using Matplotlib. While 2D scatter plots are common, 3D scatter plots can provide a new perspective and deeper understanding in some cases.

Overview of 3D Scatter Plots in Matplotlib

Just like a 2D scatter plot, the 3D version uses dots to represent data points in three-dimensional space. The major difference, of course, is the addition of a third axis (z-axis) to visualize data in a three-dimensional space. For those familiar with 2D scatter plots, transitioning to 3D is straightforward with only a few tweaks in the code.

Setting Up for a 3D Scatter Plot

Before we delve into creating the 3D scatter plot, it’s essential to import the necessary module. The axes3d module from mpl_toolkits.mplot3d is a must:

1
from mpl_toolkits.mplot3d import axes3d

Once imported, it’s time to give your data a z-axis and set the figure to project in 3D:

1
ax = fig.gca(projection='3d')

3d scatter plot with Matplotlib

A Comprehensive Example of a 3D Scatter Plot

Let’s walk through a detailed example to create a vibrant 3D scatter plot:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d

# Data preparation
N = 60
g1 = (0.6 + 0.6 * np.random.rand(N), np.random.rand(N),0.4+0.1*np.random.rand(N))
g2 = (0.4+0.3 * np.random.rand(N), 0.5*np.random.rand(N),0.1*np.random.rand(N))
g3 = (0.3*np.random.rand(N),0.3*np.random.rand(N),0.3*np.random.rand(N))

data = (g1, g2, g3)
colors = ("red", "green", "blue")
groups = ("coffee", "tea", "water")

# Visualization
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, axisbg="1.0")
ax = fig.gca(projection='3d')

for data, color, group in zip(data, colors, groups):
x, y, z = data
ax.scatter(x, y, z, alpha=0.8, c=color, edgecolors='none', s=30, label=group)

plt.title('Matplot 3d scatter plot')
plt.legend(loc=2)
plt.show()

In this example, we’ve followed several crucial steps:

  • Created vectors (g1, g2, g3) representing data.
  • Defined a list of groups for labeling purposes.
  • Used the plotting functions to generate the visual representation.

Once executed, the plt.show() command will display the final 3D scatter plot.

Curious about more Matplotlib visualizations? Navigate through:
Previous Tutorial or Next Tutorial.






Leave a Reply: