Vega-Altair: A declarative statistical visualization library for Python.
npx @tessl/cli install tessl/pypi-altair@5.5.00
# Altair
1
2
A declarative statistical visualization library for Python that provides a simple, friendly, and consistent API built on top of the Vega-Lite JSON specification. Altair enables developers to create beautiful and effective visualizations with minimal code by focusing on describing what they want rather than how to draw it.
3
4
## Package Information
5
6
- **Package Name**: altair
7
- **Language**: Python
8
- **Installation**: `pip install altair`
9
- **Optional Dependencies**: `pip install altair[all]` for full functionality
10
11
## Core Imports
12
13
```python
14
import altair as alt
15
```
16
17
For specific components:
18
19
```python
20
from altair import Chart, param, expr, datum
21
```
22
23
## Basic Usage
24
25
```python
26
import altair as alt
27
import pandas as pd
28
29
# Enable Altair in Jupyter notebooks
30
alt.data_transformers.enable('json')
31
32
# Create sample data
33
data = pd.DataFrame({
34
'x': [1, 2, 3, 4, 5],
35
'y': [2, 5, 3, 8, 7],
36
'category': ['A', 'B', 'A', 'B', 'A']
37
})
38
39
# Create a simple scatter plot
40
chart = alt.Chart(data).mark_circle(size=100).encode(
41
x='x:Q',
42
y='y:Q',
43
color='category:N'
44
).properties(
45
title='Simple Scatter Plot'
46
)
47
48
chart.show()
49
50
# Create a bar chart with aggregation
51
bar_chart = alt.Chart(data).mark_bar().encode(
52
x='category:N',
53
y='mean(y):Q',
54
color='category:N'
55
).properties(
56
title='Average Y by Category'
57
)
58
59
bar_chart.show()
60
```
61
62
## Architecture
63
64
Altair follows a grammar of graphics approach where visualizations are constructed by combining data, marks, encodings, and transformations:
65
66
- **Chart**: The primary object that combines data with visual specifications
67
- **Marks**: Visual elements (point, line, bar, area, etc.) that represent data
68
- **Encodings**: Mappings from data fields to visual properties (position, color, size, etc.)
69
- **Transformations**: Data processing operations (filter, aggregate, calculate, etc.)
70
- **Parameters**: Interactive elements for dynamic visualizations
71
- **Expressions**: Calculated fields and conditional logic using Vega expressions
72
73
This declarative approach allows complex visualizations to be built compositionally, with clear separation between data preparation, visual encoding, and interactivity.
74
75
## Capabilities
76
77
### Chart Creation
78
79
Core functionality for creating and configuring charts with data, marks, and encodings. The Chart class is the primary interface for building visualizations.
80
81
```python { .api }
82
class Chart:
83
def __init__(self, data=None, **kwargs): ...
84
def mark_point(self, **kwargs): ...
85
def mark_line(self, **kwargs): ...
86
def mark_bar(self, **kwargs): ...
87
def mark_area(self, **kwargs): ...
88
def encode(self, **kwargs): ...
89
def transform_filter(self, predicate): ...
90
def properties(self, **kwargs): ...
91
```
92
93
[Chart Creation](./chart-creation.md)
94
95
### Data Handling
96
97
Data transformation, loading, and preprocessing functionality including support for pandas DataFrames, CSV/JSON files, and various data formats.
98
99
```python { .api }
100
def to_json(data, **kwargs): ...
101
def to_csv(data, **kwargs): ...
102
def limit_rows(max_rows=5000): ...
103
def sample(n=None, frac=None): ...
104
105
# Data transformers registry
106
data_transformers = PluginRegistry()
107
```
108
109
[Data Handling](./data-handling.md)
110
111
### Encodings & Channels
112
113
Visual encoding channels that map data fields to visual properties like position, color, size, and shape. These form the core of the grammar of graphics implementation.
114
115
```python { .api }
116
class X:
117
def __init__(self, field=None, type=None, **kwargs): ...
118
119
class Y:
120
def __init__(self, field=None, type=None, **kwargs): ...
121
122
class Color:
123
def __init__(self, field=None, type=None, **kwargs): ...
124
125
class Size:
126
def __init__(self, field=None, type=None, **kwargs): ...
127
```
128
129
[Encodings & Channels](./encodings-channels.md)
130
131
### Transformations
132
133
Data transformation operations that can be applied to datasets within chart specifications, including filtering, aggregation, binning, and calculations.
134
135
```python { .api }
136
# Available as Chart methods
137
def transform_filter(self, predicate): ...
138
def transform_aggregate(self, **kwargs): ...
139
def transform_calculate(self, **kwargs): ...
140
def transform_bin(self, **kwargs): ...
141
def transform_lookup(self, **kwargs): ...
142
```
143
144
[Transformations](./transformations.md)
145
146
### Parameters & Interactions
147
148
Interactive parameters and selections that enable dynamic, interactive visualizations with user input controls and cross-filtering.
149
150
```python { .api }
151
def param(name=None, value=None, bind=None, **kwargs): ...
152
153
class Parameter:
154
def __init__(self, **kwargs): ...
155
156
def selection_point(**kwargs): ...
157
def selection_interval(**kwargs): ...
158
```
159
160
[Parameters & Interactions](./parameters-interactions.md)
161
162
### Expressions & Conditions
163
164
Expression system for calculated fields, conditional logic, and dynamic values using Vega expression language with mathematical, string, and logical operations.
165
166
```python { .api }
167
class ExpressionAPI:
168
# Mathematical functions
169
def abs(self, expr): ...
170
def sin(self, expr): ...
171
def log(self, expr): ...
172
173
# String functions
174
def upper(self, expr): ...
175
def length(self, expr): ...
176
177
# Conditional functions
178
def if_(self, test, then, else_): ...
179
180
expr = ExpressionAPI()
181
datum = DatumExpression()
182
```
183
184
[Expressions & Conditions](./expressions-conditions.md)
185
186
### Chart Composition
187
188
Functions for combining multiple charts through layering, concatenation, faceting, and repetition to create complex multi-view visualizations.
189
190
```python { .api }
191
def layer(*charts, **kwargs): ...
192
def hconcat(*charts, **kwargs): ...
193
def vconcat(*charts, **kwargs): ...
194
def concat(*charts, **kwargs): ...
195
def repeat(**kwargs): ...
196
```
197
198
[Chart Composition](./chart-composition.md)
199
200
### Configuration & Theming
201
202
Theme system and configuration options for customizing chart appearance, including axis styling, color schemes, and layout properties.
203
204
```python { .api }
205
# Theme registry
206
theme = ThemeRegistry()
207
208
class Config:
209
def __init__(self, **kwargs): ...
210
211
class AxisConfig:
212
def __init__(self, **kwargs): ...
213
214
class LegendConfig:
215
def __init__(self, **kwargs): ...
216
```
217
218
[Configuration & Theming](./configuration-theming.md)
219
220
### Rendering & Output
221
222
Display and output options for charts including Jupyter notebook integration, static image export, and HTML generation.
223
224
```python { .api }
225
# Renderer registry
226
renderers = PluginRegistry()
227
228
class Chart:
229
def show(self): ...
230
def save(self, filename, **kwargs): ...
231
def to_dict(self): ...
232
def to_json(self): ...
233
```
234
235
[Rendering & Output](./rendering-output.md)
236
237
### Utility Functions
238
239
Utility functions and constants for working with Altair specifications and handling common tasks.
240
241
```python { .api }
242
def parse_shorthand(shorthand, data=None):
243
"""
244
Parse encoding shorthand string into field name, data type, and aggregate.
245
246
Parameters:
247
- shorthand: Shorthand string (e.g., 'field:Q', 'mean(field):Q')
248
- data: Optional data for field validation
249
250
Returns:
251
dict: Parsed components
252
"""
253
254
class Undefined:
255
"""Sentinel object representing undefined/unspecified values."""
256
257
# Exception classes
258
class AltairDeprecationWarning(UserWarning):
259
"""Warning for deprecated Altair functionality."""
260
261
class MaxRowsError(Exception):
262
"""Exception raised when data exceeds maximum allowed rows."""
263
264
# Version constants
265
VEGALITE_VERSION: str # Vega-Lite specification version
266
VEGA_VERSION: str # Vega version
267
VEGAEMBED_VERSION: str # Vega-Embed version
268
SCHEMA_VERSION: str # Schema version
269
SCHEMA_URL: str # Schema URL
270
```
271
272
## Common Types
273
274
```python { .api }
275
from typing import Union, Dict, List, Any, Optional
276
277
# Data types
278
ChartDataType = Union[pd.DataFrame, str, dict, list]
279
FieldName = str
280
DataType = Union['quantitative', 'ordinal', 'nominal', 'temporal']
281
282
# Basic chart configuration
283
class ChartConfig:
284
width: Optional[int] = None
285
height: Optional[int] = None
286
title: Optional[str] = None
287
background: Optional[str] = None
288
289
# Encoding types
290
EncodingType = Union[str, Dict[str, Any]]
291
ScaleType = Union['linear', 'log', 'sqrt', 'symlog', 'time', 'utc', 'ordinal', 'point', 'band']
292
```