Plotly Cheatsheet
Installation
| Platform/Method | Command |
|---|
| Python (pip) | pip install plotly |
| Python with all dependencies | pip install plotly[all] |
| Conda (recommended) | conda install -c conda-forge plotly |
| Jupyter Notebook support | pip install "notebook>=5.3" "ipywidgets>=7.5" |
| JupyterLab 3.x | pip install jupyterlab "ipywidgets>=7.6" |
| Dash framework | pip install dash |
| Static image export | pip install -U kaleido |
| Development version | pip install git+https://github.com/plotly/plotly.py.git |
| Upgrade to latest | pip install --upgrade plotly |
| Verify installation | python -c "import plotly; print(plotly.__version__)" |
Basic Commands - Plotly Express (High-Level API)
| Command | Description |
|---|
import plotly.express as px | Import Plotly Express for quick visualizations |
px.scatter(df, x='col1', y='col2') | Create scatter plot from DataFrame |
px.line(df, x='date', y='value') | Create line chart for time series |
px.bar(df, x='category', y='value') | Create vertical bar chart |
px.bar(df, x='value', y='category', orientation='h') | Create horizontal bar chart |
px.histogram(df, x='values', nbins=20) | Create histogram with specified bins |
px.box(df, x='category', y='values') | Create box plot for distribution analysis |
px.violin(df, x='category', y='values') | Create violin plot showing distribution |
px.pie(df, values='amount', names='category') | Create pie chart |
px.pie(df, values='amount', names='category', hole=0.4) | Create donut chart |
px.scatter_3d(df, x='x', y='y', z='z') | Create 3D scatter plot |
px.imshow(data_matrix) | Create heatmap from 2D array |
px.density_heatmap(df, x='col1', y='col2') | Create density heatmap from data points |
px.area(df, x='date', y='value') | Create area chart |
px.funnel(df, x='value', y='stage') | Create funnel chart for conversion analysis |
fig.show() | Display figure in default renderer |
fig.show(renderer='browser') | Display figure in web browser |
fig.write_html('output.html') | Save figure as HTML file |
fig.write_image('output.png') | Save figure as PNG image |
fig.write_image('output.pdf') | Save figure as PDF |
Basic Commands - Graph Objects (Low-Level API)
| Command | Description |
|---|
import plotly.graph_objects as go | Import Graph Objects for detailed control |
go.Figure() | Create empty figure object |
go.Scatter(x=data_x, y=data_y) | Create scatter trace |
go.Scatter(mode='lines') | Create line trace |
go.Scatter(mode='markers') | Create markers-only scatter |
go.Scatter(mode='lines+markers') | Create line with markers |
go.Bar(x=categories, y=values) | Create bar trace |
go.Histogram(x=values) | Create histogram trace |
go.Box(y=values) | Create box plot trace |
go.Heatmap(z=matrix) | Create heatmap trace |
go.Scatter3d(x=x, y=y, z=z) | Create 3D scatter trace |
go.Surface(z=matrix) | Create 3D surface plot |
go.Contour(z=matrix) | Create contour plot |
fig.add_trace(trace) | Add trace to existing figure |
fig.data | Access all traces in figure |
fig.layout | Access figure layout properties |
Advanced Usage - Customization
| Command | Description |
|---|
fig.update_layout(title='Title') | Update figure title |
fig.update_layout(template='plotly_dark') | Apply dark theme template |
fig.update_layout(width=800, height=600) | Set figure dimensions |
fig.update_xaxes(title='X Label') | Update x-axis properties |
fig.update_yaxes(title='Y Label', type='log') | Update y-axis with log scale |
fig.update_traces(marker_size=10) | Update all trace properties |
fig.update_traces(line_color='red', selector=dict(name='trace1')) | Update specific trace by name |
px.scatter(df, color='category') | Color points by categorical variable |
px.scatter(df, size='value') | Size points by numerical variable |
px.scatter(df, hover_data=['col1', 'col2']) | Add custom hover information |
px.scatter(df, facet_col='category') | Create small multiples by column |
px.scatter(df, facet_row='cat1', facet_col='cat2') | Create 2D grid of subplots |
px.scatter(df, trendline='ols') | Add ordinary least squares trendline |
px.scatter(df, marginal_x='histogram') | Add marginal histogram on x-axis |
px.scatter(df, color_continuous_scale='Viridis') | Set continuous color scale |
Advanced Usage - Subplots and Multiple Axes
| Command | Description |
|---|
from plotly.subplots import make_subplots | Import subplot functionality |
make_subplots(rows=2, cols=2) | Create 2x2 subplot grid |
make_subplots(specs=[[{"secondary_y": True}]]) | Create figure with secondary y-axis |
fig.add_trace(trace, row=1, col=2) | Add trace to specific subplot |
make_subplots(subplot_titles=('Plot 1', 'Plot 2')) | Create subplots with titles |
make_subplots(shared_xaxes=True) | Create subplots sharing x-axis |
make_subplots(vertical_spacing=0.1) | Set vertical spacing between subplots |
fig.update_xaxes(matches='x') | Synchronize x-axes across subplots |
fig.update_yaxes(title_text='Y1', secondary_y=False) | Update primary y-axis |
fig.update_yaxes(title_text='Y2', secondary_y=True) | Update secondary y-axis |
Advanced Usage - Annotations and Shapes
| Command | Description |
|---|
fig.add_annotation(x=2, y=5, text='Note') | Add text annotation at coordinates |
fig.add_annotation(showarrow=True, arrowhead=2) | Add annotation with arrow |
fig.add_shape(type='rect', x0=1, y0=2, x1=3, y1=4) | Add rectangle shape |
fig.add_shape(type='line', x0=0, y0=0, x1=5, y1=5) | Add line shape |
fig.add_shape(type='circle', x0=1, y0=1, x1=3, y1=3) | Add circle shape |
fig.add_hline(y=5, line_dash='dash') | Add horizontal reference line |
fig.add_vline(x=3, line_color='red') | Add vertical reference line |
fig.add_hrect(y0=2, y1=4, fillcolor='blue', opacity=0.2) | Add horizontal rectangle region |
fig.add_vrect(x0=1, x1=2, fillcolor='green', opacity=0.2) | Add vertical rectangle region |
Configuration - Layout Options
# Complete layout configuration
fig.update_layout(
title=dict(
text='Chart Title',
font=dict(size=24, color='navy'),
x=0.5, # Center title
xanchor='center'
),
xaxis=dict(
title='X Axis Label',
showgrid=True,
gridcolor='lightgray',
zeroline=True,
showline=True,
linecolor='black'
),
yaxis=dict(
title='Y Axis Label',
showgrid=True,
gridcolor='lightgray',
range=[0, 100] # Fixed range
),
plot_bgcolor='rgba(0,0,0,0)', # Transparent background
paper_bgcolor='white',
font=dict(family='Arial', size=12, color='black'),
showlegend=True,
legend=dict(
x=1,
y=1,
xanchor='right',
yanchor='top',
bgcolor='rgba(255,255,255,0.5)'
),
hovermode='closest', # or 'x', 'y', 'x unified'
width=800,
height=600,
margin=dict(l=50, r=50, t=50, b=50)
)
Configuration - Trace Styling
# Scatter plot styling
fig.update_traces(
marker=dict(
size=10,
color='blue',
opacity=0.7,
line=dict(width=2, color='darkblue'),
symbol='circle' # or 'square', 'diamond', 'cross', etc.
),
line=dict(
color='red',
width=3,
dash='dash' # or 'dot', 'dashdot', 'solid'
),
textposition='top center',
textfont=dict(size=12, color='black')
)
# Bar chart styling
fig.update_traces(
marker=dict(
color='lightblue',
line=dict(color='darkblue', width=1.5)
),
texttemplate='%{y:.2f}',
textposition='outside'
)
Configuration - Renderer Settings
import plotly.io as pio
# Set default renderer
pio.renderers.default = 'browser' # or 'notebook', 'jupyterlab', 'vscode'
# Check available renderers
print(pio.renderers)
# Set default template
pio.templates.default = 'plotly_dark'
# Available templates: plotly, plotly_white, plotly_dark, ggplot2,
# seaborn, simple_white, none
Common Use Cases
Use Case 1: Time Series Analysis with Range Slider
import plotly.express as px
import pandas as pd
# Create time series data
df = pd.DataFrame({
'date': pd.date_range('2023-01-01', periods=365),
'value': np.random.randn(365).cumsum()
})
# Create interactive time series
fig = px.line(df, x='date', y='value', title='Time Series with Range Slider')
# Add range slider and buttons
fig.update_xaxes(
rangeslider_visible=True,
rangeselector=dict(
buttons=list([
dict(count=1, label="1m", step="month", stepmode="backward"),
dict(count=6, label="6m", step="month", stepmode="backward"),
dict(count=1, label="YTD", step="year", stepmode="todate"),
dict(count=1, label="1y", step="year", stepmode="backward"),
dict(step="all")
])
)
)
fig.show()
Use Case 2: Multi-Metric Dashboard with Subplots
from plotly.subplots import make_subplots
import plotly.graph_objects as go
# Create subplot grid
fig = make_subplots(
rows=2, cols=2,
subplot_titles=('Sales Trend', 'Category Distribution',
'Regional Performance', 'Monthly Comparison'),
specs=[[{'type': 'scatter'}, {'type': 'bar'}],
[{'type': 'pie'}, {'type': 'box'}]]
)
# Add line chart
fig.add_trace(
go.Scatter(x=[1,2,3,4], y=[10,15,13,17], mode='lines+markers', name='Sales'),
row=1, col=1
)
# Add bar chart
fig.add_trace(
go.Bar(x=['A','B','C'], y=[20,30,25], name='Categories'),
row=1, col=2
)
# Add pie chart
fig.add_trace(
go.Pie(labels=['East','West','North','South'], values=[30,25,20,25]),
row=2, col=1
)
# Add box plot
fig.add_trace(
go.Box(y=[10,12,15,18,20,22,25,28,30], name='Distribution'),
row=2, col=2
)
fig.update_layout(height=800, showlegend=False, title_text='Business Dashboard')
fig.show()
Use Case 3: Correlation Heatmap with Annotations
import plotly.express as px
import pandas as pd
import numpy as np
# Create sample correlation matrix
df = pd.DataFrame(np.random.randn(100, 5), columns=['A', 'B', 'C', 'D', 'E'])
corr_matrix = df.corr()
# Create annotated heatmap
fig = px.imshow(
corr_matrix,
text_auto='.2f', # Show values with 2 decimal places
aspect='auto',
color_continuous_scale='RdBu_r', # Red-Blue reversed
zmin=-1, zmax=1 # Correlation range
)
fig.update_layout(
title='Correlation Matrix',
xaxis_title='Variables',
yaxis_title='Variables'
)
fig.show()
Use Case 4: Interactive 3D Scatter with Custom Hover
import plotly.express as px
import pandas as pd
import numpy as np
# Create 3D dataset
df = pd.DataFrame({
'x': np.random.randn(200),
'y': np.random.randn(200),
'z': np.random.randn(200),
'category': np.random.choice(['A', 'B', 'C'], 200),
'size': np.random.randint(5, 30, 200),
'label': [f'Point {i}' for i in range(200)]
})
# Create 3D scatter
fig = px.scatter_3d(
df, x='x', y='y', z='z',
color='category',
size='size',
hover_data=['label', 'size'],
title='3D Scatter Plot with Categories'
)
# Customize 3D scene
fig.update_layout(
scene=dict(
xaxis_title='X Axis',
yaxis_title='Y Axis',
zaxis_title='Z Axis',
camera=dict(eye=dict(x=1.5, y=1.5, z=1.5))
)
)
fig.show()
Use Case 5: Animated Scatter Plot
import plotly.express as px
# Create data with time dimension
df = pd.DataFrame({
'year': [2020]*5 + [2021]*5 + [2022]*5,
'country': ['A', 'B', 'C', 'D', 'E'] * 3,
'gdp': np.random.randint(1000, 5000, 15),
'population': np.random.randint(10, 100, 15)
})
# Create animated scatter
fig = px.scatter(
df, x='gdp', y='population',
animation_frame='year',
animation_group='country',
size='population',
color='country',
hover_name='country',
size_max=55,
range_x=[0, 6000],
range_y=[0, 120],
title='GDP vs Population Over Time'
)
fig.update_layout(transition_duration=500)
fig.show()
Best Practices
- Use Plotly Express for rapid prototyping: Start with
px for quick visualizations, then switch to go (Graph Objects) when you need fine-grained control over every element
- Leverage templates for consistency: Set a default template with
pio.templates.default to maintain consistent styling across all visualizations in your project
- Optimize for large datasets: For datasets with >10k points, consider using
scattergl instead of scatter, or use datashader for pre-aggregation before plotting
- Make visualizations accessible: Always include axis labels, titles, and legends. Use colorblind-friendly palettes like
plotly.colors.qualitative.Safe
- Export considerations: Use
kaleido for high-quality static exports. For web embedding, use fig.write_html(include_plotlyjs='cdn') to reduce file size
- Interactive features: Enable
hovermode='x unified' for time series to compare multiple traces at the same x-value simultaneously
- Memory management: When creating multiple figures in loops, explicitly call
fig = None or use context managers to free memory
- Version control: Save figure configurations as JSON with
fig.to_json() for reproducibility and version control of visualizations
Troubleshooting
| Issue | Solution |
|---|
| Figure not displaying in Jupyter | Install widgets: pip install "ipywidgets>=7.5" and restart kernel. Check renderer: pio.renderers.default = 'notebook' |
| ”No module named ‘plotly’” error | Install plotly: pip install plotly. If using conda, try: conda install -c conda-forge plotly |
| Static image export fails | Install kaleido: pip install -U kaleido. For older systems, try: conda install -c plotly plotly-orca |
| Slow rendering with large datasets | Switch to WebGL: use go.Scattergl() instead of go.Scatter(), or downsample data before plotting |
| Figures too small in output | Set dimensions explicitly: fig.update_layout(width=1200, height=800) or use fig.show(config={'responsive': True}) |
| Legend overlapping plot area | Reposition legend: fig.update_layout(legend=dict(x=1.05, y=1, xanchor='left')) or set showlegend=False |
| Hover labels cut off | Increase margins: fig.update_layout(margin=dict(l=100, r=100, t=100, b=100)) |
| Colors not showing correctly | Ensure color column is correct type. For categorical: convert to string. For continuous: ensure numeric values |
| Animation not working | Verify animation_frame column exists and has multiple unique values. Check data is sorted by animation frame |
| PDF export has missing elements | Use SVG as intermediate: fig.write_image('file.svg') then convert to PDF, or use fig.write_image('file.pdf', engine='kaleido') |
| Memory error with subplots | Create subplots incrementally, clearing unused figures. Use del fig and garbage collection: import gc; gc.collect() |