0
# Rendering & Output
1
2
Display and output options for charts including Jupyter notebook integration, static image export, and HTML generation. Altair provides flexible rendering backends for different environments and use cases.
3
4
## Capabilities
5
6
### Renderer Registry
7
8
Central registry for managing different rendering backends that control how charts are displayed and exported.
9
10
```python { .api }
11
class RendererRegistry:
12
def enable(self, name, **kwargs):
13
"""
14
Enable a renderer by name.
15
16
Parameters:
17
- name: Renderer name ('default', 'html', 'png', 'svg', 'pdf', 'json', 'mimebundle')
18
- **kwargs: Renderer-specific options
19
"""
20
21
def register(self, name, renderer_func):
22
"""
23
Register a new renderer function.
24
25
Parameters:
26
- name: Renderer name
27
- renderer_func: Function that renders chart specifications
28
"""
29
30
def get(self):
31
"""Get current active renderer."""
32
33
@property
34
def active(self):
35
"""Get name of active renderer."""
36
37
def names(self):
38
"""Get list of available renderer names."""
39
40
# Global renderer registry
41
renderers = RendererRegistry()
42
```
43
44
### Chart Display Methods
45
46
Core methods available on Chart objects for displaying and exporting visualizations.
47
48
```python { .api }
49
class Chart:
50
def show(self):
51
"""
52
Display chart using the active renderer.
53
54
In Jupyter notebooks, displays inline.
55
In other environments, may open browser or save file.
56
"""
57
58
def save(
59
self,
60
filename,
61
format=None,
62
mode=None,
63
vegalite_version=None,
64
vega_version=None,
65
vegaembed_version=None,
66
embed_options=None,
67
json_kwds=None,
68
webdriver=None,
69
scale_factor=1,
70
**kwargs
71
):
72
"""
73
Save chart to file in various formats.
74
75
Parameters:
76
- filename: Output filename with extension
77
- format: Output format ('html', 'png', 'svg', 'pdf', 'json')
78
- mode: Save mode ('vega-lite' or 'vega')
79
- vegalite_version: Vega-Lite version to use
80
- vega_version: Vega version to use
81
- vegaembed_version: Vega-Embed version to use
82
- embed_options: Vega-Embed configuration options
83
- json_kwds: JSON serialization options
84
- webdriver: Selenium webdriver for image export
85
- scale_factor: Scale factor for image export
86
"""
87
88
def serve(
89
self,
90
port=8888,
91
open=True,
92
ip='127.0.0.1',
93
n_retries=50,
94
files=None,
95
jupyter_warning=True,
96
inline=False,
97
**kwargs
98
):
99
"""
100
Serve chart in local web server.
101
102
Parameters:
103
- port: Server port number
104
- open: Whether to open browser automatically
105
- ip: Server IP address
106
- n_retries: Number of port retries
107
- files: Additional files to serve
108
- jupyter_warning: Show Jupyter warning
109
- inline: Inline mode for Jupyter
110
"""
111
112
def to_dict(self, validate=True, format='vega-lite', context=None):
113
"""
114
Convert chart to dictionary specification.
115
116
Parameters:
117
- validate: Whether to validate against schema
118
- format: Output format ('vega-lite' or 'vega')
119
- context: Conversion context
120
121
Returns:
122
dict: Chart specification dictionary
123
"""
124
125
def to_json(
126
self,
127
validate=True,
128
indent=2,
129
sort_keys=True,
130
**kwargs
131
):
132
"""
133
Convert chart to JSON string.
134
135
Parameters:
136
- validate: Whether to validate against schema
137
- indent: JSON indentation
138
- sort_keys: Whether to sort dictionary keys
139
140
Returns:
141
str: JSON representation of chart
142
"""
143
144
def to_html(
145
self,
146
base_url='https://cdn.jsdelivr.net/npm/',
147
output_div='vis',
148
embed_options=None,
149
json_kwds=None,
150
fullhtml=True,
151
requirejs=False,
152
**kwargs
153
):
154
"""
155
Convert chart to standalone HTML.
156
157
Parameters:
158
- base_url: Base URL for Vega libraries
159
- output_div: HTML div ID for chart
160
- embed_options: Vega-Embed options
161
- json_kwds: JSON serialization options
162
- fullhtml: Whether to include full HTML document
163
- requirejs: Whether to use RequireJS
164
165
Returns:
166
str: HTML representation of chart
167
"""
168
```
169
170
### VegaLite Renderer Class
171
172
Core renderer class that handles Vega-Lite specification rendering.
173
174
```python { .api }
175
class VegaLite:
176
def __init__(self, spec, **metadata):
177
"""
178
Vega-Lite renderer for chart specifications.
179
180
Parameters:
181
- spec: Vega-Lite specification dictionary
182
- **metadata: Additional metadata for rendering
183
"""
184
185
def _repr_mimebundle_(self, include=None, exclude=None):
186
"""Generate MIME bundle for Jupyter display."""
187
188
def _repr_html_(self):
189
"""Generate HTML representation for display."""
190
191
@property
192
def spec(self):
193
"""Get chart specification."""
194
```
195
196
### Jupyter Integration
197
198
Functions and classes for enhanced Jupyter notebook integration.
199
200
```python { .api }
201
class JupyterChart:
202
"""
203
Enhanced chart class with Jupyter-specific capabilities.
204
205
Provides interactive widgets and enhanced display options
206
for Jupyter notebook environments.
207
"""
208
209
def __init__(self, chart):
210
"""
211
Create JupyterChart from regular Chart.
212
213
Parameters:
214
- chart: Altair Chart object
215
"""
216
217
def show(self):
218
"""Display chart with Jupyter optimizations."""
219
220
def display(self):
221
"""Alternative display method for Jupyter."""
222
223
def load_ipython_extension(ipython):
224
"""
225
Load Altair IPython extension for magic commands.
226
227
Parameters:
228
- ipython: IPython instance
229
"""
230
```
231
232
### Version Constants
233
234
Version information for the underlying visualization libraries.
235
236
```python { .api }
237
# Library version constants
238
VEGA_VERSION: str # Vega library version
239
VEGALITE_VERSION: str # Vega-Lite library version
240
VEGAEMBED_VERSION: str # Vega-Embed library version
241
242
# Schema information
243
SCHEMA_VERSION: str # Vega-Lite schema version
244
SCHEMA_URL: str # URL to Vega-Lite schema
245
```
246
247
## Usage Examples
248
249
### Basic Display
250
251
```python
252
import altair as alt
253
254
chart = alt.Chart(data).mark_circle().encode(
255
x='x:Q',
256
y='y:Q'
257
)
258
259
# Display in current environment
260
chart.show()
261
262
# In Jupyter notebooks, can also just evaluate
263
chart # Displays automatically
264
```
265
266
### Renderer Configuration
267
268
```python
269
# Check available renderers
270
print(alt.renderers.names())
271
272
# Enable specific renderer
273
alt.renderers.enable('html')
274
alt.renderers.enable('mimebundle') # Default for Jupyter
275
276
# Check active renderer
277
print(alt.renderers.active)
278
```
279
280
### Saving Charts
281
282
```python
283
# Save as HTML
284
chart.save('chart.html')
285
286
# Save as PNG (requires selenium and webdriver)
287
chart.save('chart.png', scale_factor=2)
288
289
# Save as SVG
290
chart.save('chart.svg')
291
292
# Save as PDF
293
chart.save('chart.pdf')
294
295
# Save JSON specification
296
chart.save('chart.json')
297
298
# Save with custom embed options
299
chart.save(
300
'chart.html',
301
embed_options={'actions': False, 'theme': 'dark'}
302
)
303
```
304
305
### HTML Export with Custom Options
306
307
```python
308
# Generate standalone HTML
309
html_str = chart.to_html(
310
embed_options={
311
'theme': 'dark',
312
'actions': {'export': True, 'source': False, 'compiled': False, 'editor': False}
313
},
314
fullhtml=True
315
)
316
317
# Write to file
318
with open('custom_chart.html', 'w') as f:
319
f.write(html_str)
320
```
321
322
### JSON Export
323
324
```python
325
# Get dictionary specification
326
spec_dict = chart.to_dict()
327
328
# Get JSON string
329
json_str = chart.to_json(indent=4)
330
331
# Save with validation disabled
332
spec_dict = chart.to_dict(validate=False)
333
```
334
335
### Local Server
336
337
```python
338
# Serve chart on local server
339
chart.serve(port=8080, open=True)
340
341
# Serve with additional files
342
chart.serve(
343
port=8888,
344
files={'data.csv': 'path/to/data.csv'}
345
)
346
```
347
348
### Jupyter-Specific Features
349
350
```python
351
# Enhanced Jupyter display
352
jupyter_chart = alt.JupyterChart(chart)
353
jupyter_chart.show()
354
355
# Using magic commands (after loading extension)
356
# %load_ext altair
357
# %%altair
358
# alt.Chart(data).mark_point().encode(x='x:Q', y='y:Q')
359
```
360
361
### Custom Renderer
362
363
```python
364
# Define custom renderer
365
def custom_png_renderer(spec, **kwargs):
366
"""Custom PNG renderer with specific settings."""
367
# Implementation would handle PNG generation
368
# with custom settings
369
pass
370
371
# Register custom renderer
372
alt.renderers.register('custom_png', custom_png_renderer)
373
alt.renderers.enable('custom_png')
374
```
375
376
### Batch Export
377
378
```python
379
# Export multiple charts
380
charts = [chart1, chart2, chart3]
381
formats = ['png', 'svg', 'html']
382
383
for i, chart in enumerate(charts):
384
for fmt in formats:
385
filename = f'chart_{i}.{fmt}'
386
chart.save(filename)
387
```
388
389
### Advanced HTML Export
390
391
```python
392
# Custom HTML template
393
html_template = """
394
<!DOCTYPE html>
395
<html>
396
<head>
397
<title>Custom Chart</title>
398
<style>
399
body {{ font-family: Arial, sans-serif; }}
400
.chart-container {{ margin: 20px; }}
401
</style>
402
</head>
403
<body>
404
<h1>My Custom Chart</h1>
405
<div class="chart-container">
406
{chart_html}
407
</div>
408
</body>
409
</html>
410
"""
411
412
chart_html = chart.to_html(fullhtml=False)
413
full_html = html_template.format(chart_html=chart_html)
414
415
with open('custom_page.html', 'w') as f:
416
f.write(full_html)
417
```
418
419
### High-Quality Image Export
420
421
```python
422
# High-DPI image export
423
chart.save(
424
'high_res_chart.png',
425
scale_factor=3, # 3x resolution
426
webdriver='chrome' # Use Chrome webdriver
427
)
428
429
# PDF export with specific settings
430
chart.save(
431
'chart.pdf',
432
embed_options={'actions': False},
433
scale_factor=2
434
)
435
```
436
437
### Programmatic Display Control
438
439
```python
440
# Conditional rendering based on environment
441
import sys
442
443
if 'ipykernel' in sys.modules:
444
# In Jupyter - use default mimebundle renderer
445
alt.renderers.enable('mimebundle')
446
chart.show()
447
elif 'bokeh' in sys.modules:
448
# In Bokeh server - use HTML renderer
449
alt.renderers.enable('html')
450
chart.show()
451
else:
452
# Command line - save to file
453
chart.save('output.html')
454
print("Chart saved to output.html")
455
```
456
457
## Types
458
459
```python { .api }
460
from typing import Union, Dict, Any, Optional, Callable, List
461
462
# Renderer function type
463
RendererFunction = Callable[[Dict[str, Any]], Any]
464
465
# Output formats
466
OutputFormat = Union['html', 'png', 'svg', 'pdf', 'json', 'vega', 'vega-lite']
467
468
# Save mode
469
SaveMode = Union['vega-lite', 'vega']
470
471
# Embed options
472
EmbedOptions = Dict[str, Any]
473
474
# MIME bundle
475
MimeBundle = Dict[str, Any]
476
477
# HTML generation options
478
class HtmlOptions:
479
base_url: str = 'https://cdn.jsdelivr.net/npm/'
480
output_div: str = 'vis'
481
embed_options: Optional[EmbedOptions] = None
482
fullhtml: bool = True
483
requirejs: bool = False
484
485
# Save options
486
class SaveOptions:
487
format: Optional[OutputFormat] = None
488
mode: Optional[SaveMode] = None
489
scale_factor: int = 1
490
webdriver: Optional[str] = None
491
embed_options: Optional[EmbedOptions] = None
492
493
# Server options
494
class ServerOptions:
495
port: int = 8888
496
open: bool = True
497
ip: str = '127.0.0.1'
498
n_retries: int = 50
499
inline: bool = False
500
```