Introduction
Plotly creates interactive, publication-quality graphs. It's ideal for dashboards and web applications where interactivity is essential.
Why Plotly?
- Interactive: Zoom, pan, hover tooltips
- Web-ready: Works with Dash, Streamlit
- Many chart types: 3D, maps, scientific charts
Basic Plotly
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
df = pd.DataFrame({
'x': [1, 2, 3, 4, 5],
'y': [10, 20, 15, 25, 30],
'category': ['A', 'B', 'A', 'B', 'A']
})
Express Plots
# Scatter plot
fig = px.scatter(df, x='x', y='y', color='category')
fig.show()
# Line plot
fig = px.line(df, x='x', y='y')
# Bar chart
fig = px.bar(df, x='category', y='y')
# Box plot
fig = px.box(df, x='category', y='y')
# Violin plot
fig = px.violin(df, x='category', y='y')
Interactive Features
# Add hover data
fig = px.scatter(df, x='x', y='y',
hover_data=['category'],
title='Interactive Plot')
# Facet plots
fig = px.scatter(df, x='x', y='y',
facet_col='category')
# Animation
fig = px.scatter(df, x='x', y='y',
animation_frame='category')
Graph Objects
# Create custom figure
fig = go.Figure()
# Add traces
fig.add_trace(go.Scatter(x=[1,2,3], y=[1,2,3],
mode='lines+markers',
name='Line 1'))
fig.add_trace(go.Bar(x=[1,2,3], y=[3,2,1]))
# Update layout
fig.update_layout(title='Custom Figure',
xaxis_title='X Axis',
yaxis_title='Y Axis',
template='plotly_dark')
3D Plots
import numpy as np
# 3D scatter
fig = px.scatter_3d(df, x='x', y='y', z='category')
# 3D surface
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)])
Dash Integration
from dash import Dash, dcc, html
import plotly.express as px
app = Dash(__name__)
app.layout = html.Div([
dcc.Graph(figure=fig),
html.H1("Dashboard Title")
])
if __name__ == '__main__':
app.run_server(debug=True)
Key Takeaways
- Plotly enables interactive web visualizations
- Use Express for quick plotting
- Graph Objects offer full customization