5 min read min read
3D Visualizations
Learn to create 3D charts with Plotly
3D Visualizations
Why 3D Charts?
3D charts help when you have three variables:
- X, Y, and Z coordinates
- Height, width, and depth
- Three related measurements
3D Scatter Plot
code.py
import plotly.express as px
import pandas as pd
df = pd.DataFrame({
'X': [1, 2, 3, 4, 5],
'Y': [2, 3, 4, 5, 6],
'Z': [1, 4, 9, 16, 25]
})
fig = px.scatter_3d(df, x='X', y='Y', z='Z')
fig.show()Click and drag to rotate!
Color in 3D
code.py
df['Category'] = ['A', 'B', 'A', 'B', 'A']
fig = px.scatter_3d(df, x='X', y='Y', z='Z', color='Category')
fig.show()Size in 3D
code.py
df['Size'] = [10, 20, 30, 40, 50]
fig = px.scatter_3d(df, x='X', y='Y', z='Z', size='Size')
fig.show()3D Line Plot
code.py
import numpy as np
t = np.linspace(0, 10, 100)
df = pd.DataFrame({
'X': np.cos(t),
'Y': np.sin(t),
'Z': t
})
fig = px.line_3d(df, x='X', y='Y', z='Z')
fig.show()Creates a spiral!
3D Surface Plot
code.py
import plotly.graph_objects as go
import numpy as np
# Create grid
x = np.linspace(-5, 5, 50)
y = np.linspace(-5, 5, 50)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))
fig = go.Figure(data=[go.Surface(z=Z, x=X, y=Y)])
fig.show()Creates a wave surface!
3D Bar Chart
code.py
import plotly.graph_objects as go
fig = go.Figure(data=[go.Mesh3d(
x=[0, 1, 0, 1, 0, 1, 0, 1],
y=[0, 0, 1, 1, 0, 0, 1, 1],
z=[0, 0, 0, 0, 1, 1, 1, 1],
color='blue',
opacity=0.5
)])
fig.show()Customize 3D View
code.py
fig = px.scatter_3d(df, x='X', y='Y', z='Z')
# Set initial camera angle
fig.update_layout(
scene_camera=dict(
eye=dict(x=1.5, y=1.5, z=1.5)
)
)
fig.show()Add Labels
code.py
fig = px.scatter_3d(df, x='X', y='Y', z='Z')
fig.update_layout(
scene=dict(
xaxis_title='X Axis',
yaxis_title='Y Axis',
zaxis_title='Z Axis'
)
)
fig.show()Complete Example
code.py
import plotly.express as px
import pandas as pd
import numpy as np
# Sample 3D data
np.random.seed(42)
n = 100
df = pd.DataFrame({
'Height': np.random.normal(170, 10, n),
'Weight': np.random.normal(70, 15, n),
'Age': np.random.randint(20, 60, n),
'Gender': np.random.choice(['Male', 'Female'], n)
})
fig = px.scatter_3d(df, x='Height', y='Weight', z='Age',
color='Gender',
title='Height, Weight, and Age',
labels={'Height': 'Height (cm)',
'Weight': 'Weight (kg)',
'Age': 'Age (years)'})
fig.show()When to Use 3D?
Good for:
- Three numeric variables
- Spatial data
- Scientific visualization
Avoid when:
- 2D would be clearer
- Presenting to non-technical audience
- Exact values matter (hard to read)
Key Points
- scatter_3d() for 3D points
- line_3d() for 3D lines
- Surface() for 3D surfaces
- Click and drag to rotate
- Use color and size for 4th variable
- 3D looks cool but can be hard to read
What's Next?
Learn to create geographic maps with Plotly.