An open-source interactive data visualization library for Python
—
Low-level figure construction interface providing complete control over traces, layout, and styling. Graph Objects enable precise customization of every visual element and support over 50 trace types for comprehensive data visualization needs.
Central figure container class and widget variant for managing traces, layout, and display operations.
class Figure:
"""
Main figure container for plotly visualizations.
Attributes:
- data: tuple of trace objects
- layout: dict or Layout object for figure configuration
"""
def __init__(self, data=None, layout=None, frames=None, skip_invalid=False):
"""
Create a new figure.
Parameters:
- data: list of trace objects or single trace
- layout: dict or Layout object for figure styling
- frames: list of frame objects for animations
- skip_invalid: bool, whether to skip invalid properties
"""
def add_trace(self, trace, row=None, col=None):
"""
Add a trace to the figure.
Parameters:
- trace: trace object (Scatter, Bar, etc.)
- row: int, subplot row (1-indexed)
- col: int, subplot column (1-indexed)
Returns:
Figure: self for method chaining
"""
def add_traces(self, data, rows=None, cols=None):
"""
Add multiple traces to the figure.
Parameters:
- data: list of trace objects
- rows: list of int, subplot rows for each trace
- cols: list of int, subplot columns for each trace
Returns:
Figure: self for method chaining
"""
def update_layout(self, **kwargs):
"""
Update figure layout properties.
Parameters:
- **kwargs: layout properties to update
Returns:
Figure: self for method chaining
"""
def update_traces(self, patch=None, selector=None, row=None, col=None, **kwargs):
"""
Update trace properties.
Parameters:
- patch: dict of properties to update
- selector: dict to select which traces to update
- row: int, update traces in specific subplot row
- col: int, update traces in specific subplot column
- **kwargs: trace properties to update
Returns:
Figure: self for method chaining
"""
def show(self, renderer=None, validate=True, **kwargs):
"""
Display the figure.
Parameters:
- renderer: str, rendering backend ('browser', 'notebook', etc.)
- validate: bool, whether to validate figure before showing
- **kwargs: additional display options
"""
def write_html(self, file, config=None, auto_play=True, include_plotlyjs=True,
auto_open=False, validate=True, pretty=False, **kwargs):
"""
Write figure to HTML file.
Parameters:
- file: str or file-like object, output file path
- config: dict, plotly.js configuration options
- include_plotlyjs: bool or str, how to include plotly.js
- auto_open: bool, whether to open file in browser
Returns:
str: HTML string if file is None
"""
def write_image(self, file, format=None, width=None, height=None, scale=None,
validate=True, engine=None):
"""
Write figure to static image file.
Parameters:
- file: str or file-like object, output file path
- format: str, image format ('png', 'jpg', 'pdf', 'svg')
- width: int, image width in pixels
- height: int, image height in pixels
- scale: float, image scale factor
- engine: str, image export engine ('kaleido', 'orca')
"""
class FigureWidget(Figure):
"""
Interactive figure widget for Jupyter notebooks.
Inherits all Figure methods and adds widget functionality.
"""
def __init__(self, data=None, layout=None, frames=None, skip_invalid=False):
"""
Create a new figure widget.
Parameters: same as Figure.__init__
"""Fundamental trace types for common visualization patterns.
class Scatter:
"""2D scatter plot trace."""
def __init__(self, x=None, y=None, mode=None, name=None, text=None,
textposition=None, texttemplate=None, hovertext=None,
hovertemplate=None, marker=None, line=None, connectgaps=None,
fill=None, fillcolor=None, opacity=None, visible=None,
showlegend=None, legendgroup=None, **kwargs):
"""
Create a scatter trace.
Parameters:
- x: array-like, x coordinates
- y: array-like, y coordinates
- mode: str, trace mode ('markers', 'lines', 'text', 'markers+lines', etc.)
- name: str, trace name for legend
- text: array-like, text annotations
- marker: dict, marker styling options
- line: dict, line styling options
- fill: str, area fill mode ('none', 'tozeroy', 'tonexty', etc.)
"""
class Bar:
"""Bar chart trace."""
def __init__(self, x=None, y=None, name=None, text=None, textposition=None,
texttemplate=None, hovertext=None, hovertemplate=None,
marker=None, orientation=None, width=None, offset=None,
base=None, opacity=None, visible=None, showlegend=None, **kwargs):
"""
Create a bar trace.
Parameters:
- x: array-like, x coordinates (categories for vertical bars)
- y: array-like, y coordinates (values for vertical bars)
- orientation: str, bar orientation ('v' for vertical, 'h' for horizontal)
- text: array-like, text annotations on bars
- marker: dict, bar styling options
- width: float or array, bar width
"""
class Histogram:
"""Histogram trace."""
def __init__(self, x=None, y=None, histfunc=None, histnorm=None,
nbinsx=None, nbinsy=None, autobinx=None, autobiny=None,
xbins=None, ybins=None, name=None, marker=None, opacity=None,
visible=None, showlegend=None, **kwargs):
"""
Create a histogram trace.
Parameters:
- x: array-like, data for histogram
- histfunc: str, aggregation function ('count', 'sum', 'avg', 'min', 'max')
- histnorm: str, normalization ('', 'percent', 'probability', 'density')
- nbinsx: int, number of bins for x-axis
- xbins: dict, bin configuration {'start': float, 'end': float, 'size': float}
"""
class Box:
"""Box plot trace."""
def __init__(self, x=None, y=None, name=None, boxpoints=None, boxmean=None,
notched=None, width=None, marker=None, line=None, fillcolor=None,
opacity=None, visible=None, showlegend=None, **kwargs):
"""
Create a box plot trace.
Parameters:
- x: array-like, x coordinates (categories)
- y: array-like, y coordinates (values)
- boxpoints: str, point display ('outliers', 'suspectedoutliers', 'all', False)
- boxmean: bool or str, whether to show mean ('sd' for standard deviation)
- notched: bool, whether to show notched boxes
"""Matrix-based visualization traces for continuous data representation.
class Heatmap:
"""Heatmap trace for matrix data."""
def __init__(self, z=None, x=None, y=None, colorscale=None, zmin=None,
zmax=None, zmid=None, colorbar=None, showscale=None,
text=None, texttemplate=None, hovertemplate=None,
xgap=None, ygap=None, name=None, opacity=None, visible=None, **kwargs):
"""
Create a heatmap trace.
Parameters:
- z: 2D array-like, matrix values for heatmap
- x: array-like, x-axis labels
- y: array-like, y-axis labels
- colorscale: str or list, color scale name or custom scale
- zmin: float, minimum value for color scale
- zmax: float, maximum value for color scale
- colorbar: dict, color bar configuration
- text: 2D array-like, text annotations for each cell
"""
class Contour:
"""Contour plot trace."""
def __init__(self, z=None, x=None, y=None, colorscale=None, contours=None,
line=None, fill=None, fillcolor=None, hovertemplate=None,
showscale=None, colorbar=None, name=None, opacity=None,
visible=None, **kwargs):
"""
Create a contour trace.
Parameters:
- z: 2D array-like, matrix values for contours
- x: array-like, x coordinates
- y: array-like, y coordinates
- contours: dict, contour line configuration
- line: dict, contour line styling
- fill: str, contour fill mode ('none', 'toself', etc.)
"""Three-dimensional plotting traces for spatial data representation.
class Scatter3d:
"""3D scatter plot trace."""
def __init__(self, x=None, y=None, z=None, mode=None, name=None, text=None,
textposition=None, hovertext=None, hovertemplate=None,
marker=None, line=None, connectgaps=None, opacity=None,
visible=None, showlegend=None, **kwargs):
"""
Create a 3D scatter trace.
Parameters:
- x: array-like, x coordinates
- y: array-like, y coordinates
- z: array-like, z coordinates
- mode: str, trace mode ('markers', 'lines', 'text', 'markers+lines')
- marker: dict, 3D marker styling options
- line: dict, 3D line styling options
"""
class Surface:
"""3D surface plot trace."""
def __init__(self, z=None, x=None, y=None, colorscale=None, showscale=None,
colorbar=None, contours=None, hidesurface=None,
hovertemplate=None, lighting=None, lightposition=None,
name=None, opacity=None, visible=None, **kwargs):
"""
Create a 3D surface trace.
Parameters:
- z: 2D array-like, surface height values
- x: array-like, x coordinates
- y: array-like, y coordinates
- colorscale: str or list, color scale for surface
- contours: dict, contour configuration for surface
- lighting: dict, 3D lighting effects
"""
class Mesh3d:
"""3D mesh trace."""
def __init__(self, x=None, y=None, z=None, i=None, j=None, k=None,
intensity=None, color=None, colorscale=None, showscale=None,
colorbar=None, alphahull=None, delaunayaxis=None,
hovertemplate=None, lighting=None, name=None, opacity=None,
visible=None, **kwargs):
"""
Create a 3D mesh trace.
Parameters:
- x: array-like, x coordinates of vertices
- y: array-like, y coordinates of vertices
- z: array-like, z coordinates of vertices
- i: array-like, vertex indices for triangles (first vertex)
- j: array-like, vertex indices for triangles (second vertex)
- k: array-like, vertex indices for triangles (third vertex)
- intensity: array-like, intensity values for color mapping
"""Geospatial visualization traces for mapping applications.
class Scattergeo:
"""Geographic scatter plot trace."""
def __init__(self, lat=None, lon=None, locations=None, locationmode=None,
mode=None, text=None, textposition=None, hovertext=None,
hovertemplate=None, marker=None, line=None, connectgaps=None,
fill=None, fillcolor=None, name=None, opacity=None,
visible=None, showlegend=None, **kwargs):
"""
Create a geographic scatter trace.
Parameters:
- lat: array-like, latitude coordinates
- lon: array-like, longitude coordinates
- locations: array-like, location identifiers
- locationmode: str, location matching mode ('ISO-3', 'USA-states', etc.)
- mode: str, trace mode ('markers', 'lines', 'text', 'markers+lines')
"""
class Choropleth:
"""Choropleth map trace."""
def __init__(self, locations=None, z=None, locationmode=None, geojson=None,
featureidkey=None, colorscale=None, zmin=None, zmax=None,
zmid=None, colorbar=None, showscale=None, text=None,
hovertext=None, hovertemplate=None, name=None, visible=None, **kwargs):
"""
Create a choropleth trace.
Parameters:
- locations: array-like, location identifiers
- z: array-like, values for color encoding
- locationmode: str, location matching mode
- geojson: dict, GeoJSON data for custom regions
- featureidkey: str, GeoJSON feature property for matching locations
"""Figure layout and styling configuration classes.
class Layout:
"""Figure layout configuration."""
def __init__(self, title=None, xaxis=None, yaxis=None, legend=None,
annotations=None, shapes=None, images=None, template=None,
width=None, height=None, margin=None, paper_bgcolor=None,
plot_bgcolor=None, font=None, showlegend=None, **kwargs):
"""
Create layout configuration.
Parameters:
- title: str or dict, figure title configuration
- xaxis: dict, x-axis configuration
- yaxis: dict, y-axis configuration
- legend: dict, legend configuration
- annotations: list of dict, text annotations
- shapes: list of dict, geometric shapes
- width: int, figure width in pixels
- height: int, figure height in pixels
- margin: dict, figure margins {'l': int, 'r': int, 't': int, 'b': int}
"""
class XAxis:
"""X-axis configuration."""
def __init__(self, title=None, type=None, range=None, domain=None,
tickmode=None, tick0=None, dtick=None, tickvals=None,
ticktext=None, tickangle=None, showgrid=None, gridwidth=None,
gridcolor=None, showline=None, linewidth=None, linecolor=None,
showticklabels=None, tickfont=None, **kwargs):
"""
Create x-axis configuration.
Parameters:
- title: str or dict, axis title
- type: str, axis type ('linear', 'log', 'date', 'category')
- range: list, axis range [min, max]
- tickmode: str, tick positioning ('auto', 'linear', 'array')
- tickvals: array-like, custom tick positions
- ticktext: array-like, custom tick labels
"""
class YAxis:
"""Y-axis configuration (same interface as XAxis)."""
def __init__(self, **kwargs):
"""Create y-axis configuration. Parameters same as XAxis."""
class Legend:
"""Legend configuration."""
def __init__(self, x=None, y=None, xanchor=None, yanchor=None,
orientation=None, bgcolor=None, bordercolor=None,
borderwidth=None, font=None, tracegroupgap=None, **kwargs):
"""
Create legend configuration.
Parameters:
- x: float, legend x position (0-1)
- y: float, legend y position (0-1)
- xanchor: str, x anchor ('auto', 'left', 'center', 'right')
- yanchor: str, y anchor ('auto', 'top', 'middle', 'bottom')
- orientation: str, legend orientation ('v', 'h')
"""import plotly.graph_objects as go
import numpy as np
# Basic scatter plot with custom styling
fig = go.Figure()
fig.add_trace(go.Scatter(
x=[1, 2, 3, 4],
y=[10, 11, 12, 13],
mode='markers+lines',
name='Trace 1',
marker=dict(size=10, color='red'),
line=dict(width=3, dash='dash')
))
fig.update_layout(
title='Custom Scatter Plot',
xaxis_title='X Axis',
yaxis_title='Y Axis',
showlegend=True
)
fig.show()
# Multiple traces with different types
fig = go.Figure()
# Add bar chart
fig.add_trace(go.Bar(
x=['A', 'B', 'C', 'D'],
y=[1, 3, 2, 4],
name='Bars',
yaxis='y'
))
# Add line chart on secondary y-axis
fig.add_trace(go.Scatter(
x=['A', 'B', 'C', 'D'],
y=[100, 200, 150, 250],
mode='lines+markers',
name='Lines',
yaxis='y2'
))
# Update layout for dual y-axes
fig.update_layout(
xaxis=dict(domain=[0.1, 1]),
yaxis=dict(title='Primary Y-axis', side='left'),
yaxis2=dict(title='Secondary Y-axis', side='right', overlaying='y'),
title='Multi-trace Chart with Dual Y-axes'
)
fig.show()
# 3D surface plot
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.update_layout(
title='3D Surface Plot',
scene=dict(
xaxis_title='X Axis',
yaxis_title='Y Axis',
zaxis_title='Z Axis'
)
)
fig.show()Install with Tessl CLI
npx tessl i tessl/pypi-plotly