0
# Graph Objects Interface
1
2
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.
3
4
## Capabilities
5
6
### Core Figure Management
7
8
Central figure container class and widget variant for managing traces, layout, and display operations.
9
10
```python { .api }
11
class Figure:
12
"""
13
Main figure container for plotly visualizations.
14
15
Attributes:
16
- data: tuple of trace objects
17
- layout: dict or Layout object for figure configuration
18
"""
19
20
def __init__(self, data=None, layout=None, frames=None, skip_invalid=False):
21
"""
22
Create a new figure.
23
24
Parameters:
25
- data: list of trace objects or single trace
26
- layout: dict or Layout object for figure styling
27
- frames: list of frame objects for animations
28
- skip_invalid: bool, whether to skip invalid properties
29
"""
30
31
def add_trace(self, trace, row=None, col=None):
32
"""
33
Add a trace to the figure.
34
35
Parameters:
36
- trace: trace object (Scatter, Bar, etc.)
37
- row: int, subplot row (1-indexed)
38
- col: int, subplot column (1-indexed)
39
40
Returns:
41
Figure: self for method chaining
42
"""
43
44
def add_traces(self, data, rows=None, cols=None):
45
"""
46
Add multiple traces to the figure.
47
48
Parameters:
49
- data: list of trace objects
50
- rows: list of int, subplot rows for each trace
51
- cols: list of int, subplot columns for each trace
52
53
Returns:
54
Figure: self for method chaining
55
"""
56
57
def update_layout(self, **kwargs):
58
"""
59
Update figure layout properties.
60
61
Parameters:
62
- **kwargs: layout properties to update
63
64
Returns:
65
Figure: self for method chaining
66
"""
67
68
def update_traces(self, patch=None, selector=None, row=None, col=None, **kwargs):
69
"""
70
Update trace properties.
71
72
Parameters:
73
- patch: dict of properties to update
74
- selector: dict to select which traces to update
75
- row: int, update traces in specific subplot row
76
- col: int, update traces in specific subplot column
77
- **kwargs: trace properties to update
78
79
Returns:
80
Figure: self for method chaining
81
"""
82
83
def show(self, renderer=None, validate=True, **kwargs):
84
"""
85
Display the figure.
86
87
Parameters:
88
- renderer: str, rendering backend ('browser', 'notebook', etc.)
89
- validate: bool, whether to validate figure before showing
90
- **kwargs: additional display options
91
"""
92
93
def write_html(self, file, config=None, auto_play=True, include_plotlyjs=True,
94
auto_open=False, validate=True, pretty=False, **kwargs):
95
"""
96
Write figure to HTML file.
97
98
Parameters:
99
- file: str or file-like object, output file path
100
- config: dict, plotly.js configuration options
101
- include_plotlyjs: bool or str, how to include plotly.js
102
- auto_open: bool, whether to open file in browser
103
104
Returns:
105
str: HTML string if file is None
106
"""
107
108
def write_image(self, file, format=None, width=None, height=None, scale=None,
109
validate=True, engine=None):
110
"""
111
Write figure to static image file.
112
113
Parameters:
114
- file: str or file-like object, output file path
115
- format: str, image format ('png', 'jpg', 'pdf', 'svg')
116
- width: int, image width in pixels
117
- height: int, image height in pixels
118
- scale: float, image scale factor
119
- engine: str, image export engine ('kaleido', 'orca')
120
"""
121
122
class FigureWidget(Figure):
123
"""
124
Interactive figure widget for Jupyter notebooks.
125
126
Inherits all Figure methods and adds widget functionality.
127
"""
128
129
def __init__(self, data=None, layout=None, frames=None, skip_invalid=False):
130
"""
131
Create a new figure widget.
132
133
Parameters: same as Figure.__init__
134
"""
135
```
136
137
### Basic Trace Types
138
139
Fundamental trace types for common visualization patterns.
140
141
```python { .api }
142
class Scatter:
143
"""2D scatter plot trace."""
144
145
def __init__(self, x=None, y=None, mode=None, name=None, text=None,
146
textposition=None, texttemplate=None, hovertext=None,
147
hovertemplate=None, marker=None, line=None, connectgaps=None,
148
fill=None, fillcolor=None, opacity=None, visible=None,
149
showlegend=None, legendgroup=None, **kwargs):
150
"""
151
Create a scatter trace.
152
153
Parameters:
154
- x: array-like, x coordinates
155
- y: array-like, y coordinates
156
- mode: str, trace mode ('markers', 'lines', 'text', 'markers+lines', etc.)
157
- name: str, trace name for legend
158
- text: array-like, text annotations
159
- marker: dict, marker styling options
160
- line: dict, line styling options
161
- fill: str, area fill mode ('none', 'tozeroy', 'tonexty', etc.)
162
"""
163
164
class Bar:
165
"""Bar chart trace."""
166
167
def __init__(self, x=None, y=None, name=None, text=None, textposition=None,
168
texttemplate=None, hovertext=None, hovertemplate=None,
169
marker=None, orientation=None, width=None, offset=None,
170
base=None, opacity=None, visible=None, showlegend=None, **kwargs):
171
"""
172
Create a bar trace.
173
174
Parameters:
175
- x: array-like, x coordinates (categories for vertical bars)
176
- y: array-like, y coordinates (values for vertical bars)
177
- orientation: str, bar orientation ('v' for vertical, 'h' for horizontal)
178
- text: array-like, text annotations on bars
179
- marker: dict, bar styling options
180
- width: float or array, bar width
181
"""
182
183
class Histogram:
184
"""Histogram trace."""
185
186
def __init__(self, x=None, y=None, histfunc=None, histnorm=None,
187
nbinsx=None, nbinsy=None, autobinx=None, autobiny=None,
188
xbins=None, ybins=None, name=None, marker=None, opacity=None,
189
visible=None, showlegend=None, **kwargs):
190
"""
191
Create a histogram trace.
192
193
Parameters:
194
- x: array-like, data for histogram
195
- histfunc: str, aggregation function ('count', 'sum', 'avg', 'min', 'max')
196
- histnorm: str, normalization ('', 'percent', 'probability', 'density')
197
- nbinsx: int, number of bins for x-axis
198
- xbins: dict, bin configuration {'start': float, 'end': float, 'size': float}
199
"""
200
201
class Box:
202
"""Box plot trace."""
203
204
def __init__(self, x=None, y=None, name=None, boxpoints=None, boxmean=None,
205
notched=None, width=None, marker=None, line=None, fillcolor=None,
206
opacity=None, visible=None, showlegend=None, **kwargs):
207
"""
208
Create a box plot trace.
209
210
Parameters:
211
- x: array-like, x coordinates (categories)
212
- y: array-like, y coordinates (values)
213
- boxpoints: str, point display ('outliers', 'suspectedoutliers', 'all', False)
214
- boxmean: bool or str, whether to show mean ('sd' for standard deviation)
215
- notched: bool, whether to show notched boxes
216
"""
217
```
218
219
### Heatmaps and Contours
220
221
Matrix-based visualization traces for continuous data representation.
222
223
```python { .api }
224
class Heatmap:
225
"""Heatmap trace for matrix data."""
226
227
def __init__(self, z=None, x=None, y=None, colorscale=None, zmin=None,
228
zmax=None, zmid=None, colorbar=None, showscale=None,
229
text=None, texttemplate=None, hovertemplate=None,
230
xgap=None, ygap=None, name=None, opacity=None, visible=None, **kwargs):
231
"""
232
Create a heatmap trace.
233
234
Parameters:
235
- z: 2D array-like, matrix values for heatmap
236
- x: array-like, x-axis labels
237
- y: array-like, y-axis labels
238
- colorscale: str or list, color scale name or custom scale
239
- zmin: float, minimum value for color scale
240
- zmax: float, maximum value for color scale
241
- colorbar: dict, color bar configuration
242
- text: 2D array-like, text annotations for each cell
243
"""
244
245
class Contour:
246
"""Contour plot trace."""
247
248
def __init__(self, z=None, x=None, y=None, colorscale=None, contours=None,
249
line=None, fill=None, fillcolor=None, hovertemplate=None,
250
showscale=None, colorbar=None, name=None, opacity=None,
251
visible=None, **kwargs):
252
"""
253
Create a contour trace.
254
255
Parameters:
256
- z: 2D array-like, matrix values for contours
257
- x: array-like, x coordinates
258
- y: array-like, y coordinates
259
- contours: dict, contour line configuration
260
- line: dict, contour line styling
261
- fill: str, contour fill mode ('none', 'toself', etc.)
262
"""
263
```
264
265
### 3D Visualization Traces
266
267
Three-dimensional plotting traces for spatial data representation.
268
269
```python { .api }
270
class Scatter3d:
271
"""3D scatter plot trace."""
272
273
def __init__(self, x=None, y=None, z=None, mode=None, name=None, text=None,
274
textposition=None, hovertext=None, hovertemplate=None,
275
marker=None, line=None, connectgaps=None, opacity=None,
276
visible=None, showlegend=None, **kwargs):
277
"""
278
Create a 3D scatter trace.
279
280
Parameters:
281
- x: array-like, x coordinates
282
- y: array-like, y coordinates
283
- z: array-like, z coordinates
284
- mode: str, trace mode ('markers', 'lines', 'text', 'markers+lines')
285
- marker: dict, 3D marker styling options
286
- line: dict, 3D line styling options
287
"""
288
289
class Surface:
290
"""3D surface plot trace."""
291
292
def __init__(self, z=None, x=None, y=None, colorscale=None, showscale=None,
293
colorbar=None, contours=None, hidesurface=None,
294
hovertemplate=None, lighting=None, lightposition=None,
295
name=None, opacity=None, visible=None, **kwargs):
296
"""
297
Create a 3D surface trace.
298
299
Parameters:
300
- z: 2D array-like, surface height values
301
- x: array-like, x coordinates
302
- y: array-like, y coordinates
303
- colorscale: str or list, color scale for surface
304
- contours: dict, contour configuration for surface
305
- lighting: dict, 3D lighting effects
306
"""
307
308
class Mesh3d:
309
"""3D mesh trace."""
310
311
def __init__(self, x=None, y=None, z=None, i=None, j=None, k=None,
312
intensity=None, color=None, colorscale=None, showscale=None,
313
colorbar=None, alphahull=None, delaunayaxis=None,
314
hovertemplate=None, lighting=None, name=None, opacity=None,
315
visible=None, **kwargs):
316
"""
317
Create a 3D mesh trace.
318
319
Parameters:
320
- x: array-like, x coordinates of vertices
321
- y: array-like, y coordinates of vertices
322
- z: array-like, z coordinates of vertices
323
- i: array-like, vertex indices for triangles (first vertex)
324
- j: array-like, vertex indices for triangles (second vertex)
325
- k: array-like, vertex indices for triangles (third vertex)
326
- intensity: array-like, intensity values for color mapping
327
"""
328
```
329
330
### Geographic Traces
331
332
Geospatial visualization traces for mapping applications.
333
334
```python { .api }
335
class Scattergeo:
336
"""Geographic scatter plot trace."""
337
338
def __init__(self, lat=None, lon=None, locations=None, locationmode=None,
339
mode=None, text=None, textposition=None, hovertext=None,
340
hovertemplate=None, marker=None, line=None, connectgaps=None,
341
fill=None, fillcolor=None, name=None, opacity=None,
342
visible=None, showlegend=None, **kwargs):
343
"""
344
Create a geographic scatter trace.
345
346
Parameters:
347
- lat: array-like, latitude coordinates
348
- lon: array-like, longitude coordinates
349
- locations: array-like, location identifiers
350
- locationmode: str, location matching mode ('ISO-3', 'USA-states', etc.)
351
- mode: str, trace mode ('markers', 'lines', 'text', 'markers+lines')
352
"""
353
354
class Choropleth:
355
"""Choropleth map trace."""
356
357
def __init__(self, locations=None, z=None, locationmode=None, geojson=None,
358
featureidkey=None, colorscale=None, zmin=None, zmax=None,
359
zmid=None, colorbar=None, showscale=None, text=None,
360
hovertext=None, hovertemplate=None, name=None, visible=None, **kwargs):
361
"""
362
Create a choropleth trace.
363
364
Parameters:
365
- locations: array-like, location identifiers
366
- z: array-like, values for color encoding
367
- locationmode: str, location matching mode
368
- geojson: dict, GeoJSON data for custom regions
369
- featureidkey: str, GeoJSON feature property for matching locations
370
"""
371
```
372
373
### Layout Configuration
374
375
Figure layout and styling configuration classes.
376
377
```python { .api }
378
class Layout:
379
"""Figure layout configuration."""
380
381
def __init__(self, title=None, xaxis=None, yaxis=None, legend=None,
382
annotations=None, shapes=None, images=None, template=None,
383
width=None, height=None, margin=None, paper_bgcolor=None,
384
plot_bgcolor=None, font=None, showlegend=None, **kwargs):
385
"""
386
Create layout configuration.
387
388
Parameters:
389
- title: str or dict, figure title configuration
390
- xaxis: dict, x-axis configuration
391
- yaxis: dict, y-axis configuration
392
- legend: dict, legend configuration
393
- annotations: list of dict, text annotations
394
- shapes: list of dict, geometric shapes
395
- width: int, figure width in pixels
396
- height: int, figure height in pixels
397
- margin: dict, figure margins {'l': int, 'r': int, 't': int, 'b': int}
398
"""
399
400
class XAxis:
401
"""X-axis configuration."""
402
403
def __init__(self, title=None, type=None, range=None, domain=None,
404
tickmode=None, tick0=None, dtick=None, tickvals=None,
405
ticktext=None, tickangle=None, showgrid=None, gridwidth=None,
406
gridcolor=None, showline=None, linewidth=None, linecolor=None,
407
showticklabels=None, tickfont=None, **kwargs):
408
"""
409
Create x-axis configuration.
410
411
Parameters:
412
- title: str or dict, axis title
413
- type: str, axis type ('linear', 'log', 'date', 'category')
414
- range: list, axis range [min, max]
415
- tickmode: str, tick positioning ('auto', 'linear', 'array')
416
- tickvals: array-like, custom tick positions
417
- ticktext: array-like, custom tick labels
418
"""
419
420
class YAxis:
421
"""Y-axis configuration (same interface as XAxis)."""
422
423
def __init__(self, **kwargs):
424
"""Create y-axis configuration. Parameters same as XAxis."""
425
426
class Legend:
427
"""Legend configuration."""
428
429
def __init__(self, x=None, y=None, xanchor=None, yanchor=None,
430
orientation=None, bgcolor=None, bordercolor=None,
431
borderwidth=None, font=None, tracegroupgap=None, **kwargs):
432
"""
433
Create legend configuration.
434
435
Parameters:
436
- x: float, legend x position (0-1)
437
- y: float, legend y position (0-1)
438
- xanchor: str, x anchor ('auto', 'left', 'center', 'right')
439
- yanchor: str, y anchor ('auto', 'top', 'middle', 'bottom')
440
- orientation: str, legend orientation ('v', 'h')
441
"""
442
```
443
444
## Usage Examples
445
446
```python
447
import plotly.graph_objects as go
448
import numpy as np
449
450
# Basic scatter plot with custom styling
451
fig = go.Figure()
452
fig.add_trace(go.Scatter(
453
x=[1, 2, 3, 4],
454
y=[10, 11, 12, 13],
455
mode='markers+lines',
456
name='Trace 1',
457
marker=dict(size=10, color='red'),
458
line=dict(width=3, dash='dash')
459
))
460
461
fig.update_layout(
462
title='Custom Scatter Plot',
463
xaxis_title='X Axis',
464
yaxis_title='Y Axis',
465
showlegend=True
466
)
467
fig.show()
468
469
# Multiple traces with different types
470
fig = go.Figure()
471
472
# Add bar chart
473
fig.add_trace(go.Bar(
474
x=['A', 'B', 'C', 'D'],
475
y=[1, 3, 2, 4],
476
name='Bars',
477
yaxis='y'
478
))
479
480
# Add line chart on secondary y-axis
481
fig.add_trace(go.Scatter(
482
x=['A', 'B', 'C', 'D'],
483
y=[100, 200, 150, 250],
484
mode='lines+markers',
485
name='Lines',
486
yaxis='y2'
487
))
488
489
# Update layout for dual y-axes
490
fig.update_layout(
491
xaxis=dict(domain=[0.1, 1]),
492
yaxis=dict(title='Primary Y-axis', side='left'),
493
yaxis2=dict(title='Secondary Y-axis', side='right', overlaying='y'),
494
title='Multi-trace Chart with Dual Y-axes'
495
)
496
fig.show()
497
498
# 3D surface plot
499
x = np.linspace(-5, 5, 50)
500
y = np.linspace(-5, 5, 50)
501
X, Y = np.meshgrid(x, y)
502
Z = np.sin(np.sqrt(X**2 + Y**2))
503
504
fig = go.Figure(data=[go.Surface(z=Z, x=x, y=y)])
505
fig.update_layout(
506
title='3D Surface Plot',
507
scene=dict(
508
xaxis_title='X Axis',
509
yaxis_title='Y Axis',
510
zaxis_title='Z Axis'
511
)
512
)
513
fig.show()
514
```