0
# Chart Creation
1
2
Core functionality for creating and configuring charts with data, marks, and encodings. The Chart class is the primary interface for building visualizations in Altair's grammar of graphics approach.
3
4
## Capabilities
5
6
### Chart Class
7
8
The main Chart class that serves as the foundation for all visualizations. It combines data with mark specifications and encodings to create declarative visualization specifications.
9
10
```python { .api }
11
class Chart:
12
def __init__(
13
self,
14
data=None,
15
encoding=None,
16
mark=None,
17
width=None,
18
height=None,
19
title=None,
20
**kwargs
21
):
22
"""
23
Create a new Chart object.
24
25
Parameters:
26
- data: Data source (DataFrame, URL, or inline data)
27
- encoding: Encoding specification dictionary
28
- mark: Mark specification (string or MarkDef object)
29
- width: Chart width in pixels
30
- height: Chart height in pixels
31
- title: Chart title
32
"""
33
34
def add_params(self, *params):
35
"""Add parameters to the chart for interactivity."""
36
37
def add_selection(self, *selections):
38
"""Add selection parameters (deprecated, use add_params)."""
39
40
def encode(self, **kwargs):
41
"""Add encodings to the chart."""
42
43
def properties(
44
self,
45
width=None,
46
height=None,
47
title=None,
48
background=None,
49
padding=None,
50
**kwargs
51
):
52
"""Set chart properties like dimensions and title."""
53
54
def resolve_axis(self, **kwargs):
55
"""Resolve axis sharing for composed charts."""
56
57
def resolve_legend(self, **kwargs):
58
"""Resolve legend sharing for composed charts."""
59
60
def resolve_scale(self, **kwargs):
61
"""Resolve scale sharing for composed charts."""
62
63
def to_dict(self):
64
"""Convert chart to Vega-Lite specification dictionary."""
65
66
def to_json(self, indent=2, **kwargs):
67
"""Convert chart to JSON string."""
68
69
def save(self, filename, **kwargs):
70
"""Save chart to file (PNG, SVG, HTML, JSON)."""
71
72
def show(self):
73
"""Display chart in current environment."""
74
75
def serve(self, port=8888, open=True):
76
"""Serve chart in local web server."""
77
78
def facet(
79
self,
80
facet=None,
81
column=None,
82
row=None,
83
data=None,
84
columns=None,
85
spacing=None,
86
**kwargs
87
):
88
"""Create faceted chart with small multiples."""
89
90
def to_html(
91
self,
92
base_url=None,
93
embed_options=None,
94
json_kwds=None,
95
**kwargs
96
):
97
"""Convert chart to HTML string."""
98
99
def repeat(self, repeat=None, **kwargs):
100
"""Create repeated chart specification."""
101
```
102
103
### Primitive Mark Methods
104
105
Methods for creating charts with basic mark types. Each method returns a new Chart object with the specified mark.
106
107
```python { .api }
108
# Point and scatter marks
109
def mark_point(
110
self,
111
filled=None,
112
opacity=None,
113
size=None,
114
stroke=None,
115
strokeWidth=None,
116
**kwargs
117
):
118
"""Create point/scatter plot marks."""
119
120
def mark_circle(
121
self,
122
opacity=None,
123
size=None,
124
stroke=None,
125
strokeWidth=None,
126
**kwargs
127
):
128
"""Create circle marks."""
129
130
def mark_square(
131
self,
132
opacity=None,
133
size=None,
134
stroke=None,
135
strokeWidth=None,
136
**kwargs
137
):
138
"""Create square marks."""
139
140
# Line marks
141
def mark_line(
142
self,
143
interpolate=None,
144
strokeDash=None,
145
strokeWidth=None,
146
opacity=None,
147
**kwargs
148
):
149
"""Create line marks."""
150
151
def mark_trail(
152
self,
153
size=None,
154
opacity=None,
155
**kwargs
156
):
157
"""Create trail marks with variable width."""
158
159
def mark_rule(
160
self,
161
strokeDash=None,
162
strokeWidth=None,
163
opacity=None,
164
**kwargs
165
):
166
"""Create rule/line marks."""
167
168
# Area marks
169
def mark_area(
170
self,
171
interpolate=None,
172
opacity=None,
173
**kwargs
174
):
175
"""Create area marks."""
176
177
def mark_bar(
178
self,
179
opacity=None,
180
cornerRadius=None,
181
**kwargs
182
):
183
"""Create bar marks."""
184
185
def mark_rect(
186
self,
187
opacity=None,
188
cornerRadius=None,
189
**kwargs
190
):
191
"""Create rectangle marks."""
192
193
# Text marks
194
def mark_text(
195
self,
196
align=None,
197
angle=None,
198
baseline=None,
199
font=None,
200
fontSize=None,
201
fontStyle=None,
202
fontWeight=None,
203
**kwargs
204
):
205
"""Create text marks."""
206
207
# Other marks
208
def mark_tick(
209
self,
210
thickness=None,
211
**kwargs
212
):
213
"""Create tick marks."""
214
215
def mark_image(
216
self,
217
url=None,
218
aspect=None,
219
**kwargs
220
):
221
"""Create image marks."""
222
223
def mark_arc(
224
self,
225
innerRadius=None,
226
outerRadius=None,
227
**kwargs
228
):
229
"""Create arc marks for pie/donut charts."""
230
```
231
232
### Composite Mark Methods
233
234
Methods for creating charts with composite marks that combine multiple primitive marks.
235
236
```python { .api }
237
def mark_boxplot(
238
self,
239
extent=None,
240
size=None,
241
**kwargs
242
):
243
"""Create box plot marks showing distribution statistics."""
244
245
def mark_errorbar(
246
self,
247
extent=None,
248
thickness=None,
249
**kwargs
250
):
251
"""Create error bar marks showing uncertainty."""
252
253
def mark_errorband(
254
self,
255
extent=None,
256
borders=None,
257
**kwargs
258
):
259
"""Create error band marks showing confidence intervals."""
260
```
261
262
### Chart Data Methods
263
264
Methods for working with chart data sources.
265
266
```python { .api }
267
def add_data(self, data):
268
"""Add or replace chart data source."""
269
270
def add_data_transformer(self, transformer):
271
"""Add data transformation function."""
272
```
273
274
## Usage Examples
275
276
### Basic Chart Creation
277
278
```python
279
import altair as alt
280
import pandas as pd
281
282
# Create data
283
data = pd.DataFrame({
284
'x': [1, 2, 3, 4, 5],
285
'y': [2, 5, 3, 8, 7]
286
})
287
288
# Create basic scatter plot
289
chart = alt.Chart(data).mark_circle(size=100).encode(
290
x='x:Q',
291
y='y:Q'
292
)
293
```
294
295
### Chart with Multiple Encodings
296
297
```python
298
# Chart with color, size, and tooltip
299
chart = alt.Chart(data).mark_circle().encode(
300
x='x:Q',
301
y='y:Q',
302
color=alt.Color('category:N', scale=alt.Scale(scheme='category10')),
303
size=alt.Size('value:Q', scale=alt.Scale(range=[50, 400])),
304
tooltip=['x:Q', 'y:Q', 'category:N', 'value:Q']
305
).properties(
306
width=400,
307
height=300,
308
title='Multi-encoded Scatter Plot'
309
)
310
```
311
312
### Chart with Transformations
313
314
```python
315
# Chart with filtering and aggregation
316
chart = alt.Chart(data).mark_bar().encode(
317
x='category:N',
318
y='mean(value):Q'
319
).transform_filter(
320
alt.datum.value > 10
321
).properties(
322
title='Filtered Average Values by Category'
323
)
324
```
325
326
## Types
327
328
```python { .api }
329
from typing import Union, Dict, Any, Optional, List
330
331
# Mark configuration types
332
MarkConfig = Dict[str, Any]
333
EncodingDict = Dict[str, Any]
334
335
# Chart properties
336
class ChartProperties:
337
width: Optional[int]
338
height: Optional[int]
339
title: Optional[Union[str, Dict[str, Any]]]
340
background: Optional[str]
341
padding: Optional[Union[int, Dict[str, int]]]
342
343
# Data types
344
DataSource = Union[pd.DataFrame, str, Dict[str, Any], List[Dict[str, Any]]]
345
346
# Mark types
347
MarkType = Union[
348
'point', 'circle', 'square', 'line', 'trail', 'rule',
349
'area', 'bar', 'rect', 'text', 'tick', 'image', 'arc',
350
'boxplot', 'errorbar', 'errorband'
351
]
352
```