pypi-streamlit

Description
A faster way to build and share data apps
Author
tessl
Last updated

How to use

npx @tessl/cli registry install tessl/pypi-streamlit@1.49.0

charts-visualizations.md docs/

1
# Charts and Visualizations
2
3
Comprehensive charting capabilities including built-in charts and third-party library integrations. Streamlit provides both simple chart functions and full integration with popular visualization libraries.
4
5
## Capabilities
6
7
### Built-in Charts
8
9
Simple, fast charts using Streamlit's native charting engine built on Altair.
10
11
```python { .api }
12
def line_chart(data=None, x=None, y=None, x_label=None, y_label=None, color=None, width=None, height=None, use_container_width=True):
13
"""
14
Display a line chart.
15
16
Parameters:
17
- data: DataFrame, array-like, or dict with chart data
18
- x (str): Column name for x-axis values
19
- y (str or list): Column name(s) for y-axis values
20
- x_label (str): Custom x-axis label
21
- y_label (str): Custom y-axis label
22
- color (str): Column name for color encoding
23
- width (int): Chart width in pixels
24
- height (int): Chart height in pixels
25
- use_container_width (bool): Use full container width
26
27
Returns:
28
None
29
"""
30
31
def area_chart(data=None, x=None, y=None, x_label=None, y_label=None, color=None, width=None, height=None, use_container_width=True, stack=None):
32
"""
33
Display an area chart.
34
35
Parameters:
36
- data: DataFrame, array-like, or dict with chart data
37
- x (str): Column name for x-axis values
38
- y (str or list): Column name(s) for y-axis values
39
- x_label (str): Custom x-axis label
40
- y_label (str): Custom y-axis label
41
- color (str): Column name for color encoding
42
- width (int): Chart width in pixels
43
- height (int): Chart height in pixels
44
- use_container_width (bool): Use full container width
45
- stack (str): Stacking mode ('normalize', 'center', or None)
46
47
Returns:
48
None
49
"""
50
51
def bar_chart(data=None, x=None, y=None, x_label=None, y_label=None, color=None, width=None, height=None, use_container_width=True, horizontal=False, stack=None):
52
"""
53
Display a bar chart.
54
55
Parameters:
56
- data: DataFrame, array-like, or dict with chart data
57
- x (str): Column name for x-axis values
58
- y (str or list): Column name(s) for y-axis values
59
- x_label (str): Custom x-axis label
60
- y_label (str): Custom y-axis label
61
- color (str): Column name for color encoding
62
- width (int): Chart width in pixels
63
- height (int): Chart height in pixels
64
- use_container_width (bool): Use full container width
65
- horizontal (bool): Create horizontal bar chart
66
- stack (str): Stacking mode ('normalize', 'center', or None)
67
68
Returns:
69
None
70
"""
71
72
def scatter_chart(data=None, x=None, y=None, x_label=None, y_label=None, color=None, size=None, width=None, height=None, use_container_width=True):
73
"""
74
Display a scatter chart.
75
76
Parameters:
77
- data: DataFrame, array-like, or dict with chart data
78
- x (str): Column name for x-axis values
79
- y (str): Column name for y-axis values
80
- x_label (str): Custom x-axis label
81
- y_label (str): Custom y-axis label
82
- color (str): Column name for color encoding
83
- size (str): Column name for size encoding
84
- width (int): Chart width in pixels
85
- height (int): Chart height in pixels
86
- use_container_width (bool): Use full container width
87
88
Returns:
89
None
90
"""
91
```
92
93
### Map Visualizations
94
95
Geographic data visualization with point overlays.
96
97
```python { .api }
98
def map(data=None, zoom=None, use_container_width=True, latitude=None, longitude=None, color=None, size=None):
99
"""
100
Display a map with points plotted on it.
101
102
Parameters:
103
- data: DataFrame with latitude and longitude columns
104
- zoom (int): Initial zoom level
105
- use_container_width (bool): Use full container width
106
- latitude (str): Column name for latitude values (default: 'latitude', 'lat')
107
- longitude (str): Column name for longitude values (default: 'longitude', 'lon', 'lng')
108
- color (str): Column name for color encoding
109
- size (str): Column name for size encoding
110
111
Returns:
112
None
113
"""
114
```
115
116
### Third-Party Chart Libraries
117
118
Integration with popular Python visualization libraries.
119
120
```python { .api }
121
def plotly_chart(figure_or_data, use_container_width=False, sharing="streamlit", theme="streamlit", **kwargs):
122
"""
123
Display an interactive Plotly chart.
124
125
Parameters:
126
- figure_or_data: Plotly figure object or data dict
127
- use_container_width (bool): Use full container width
128
- sharing (str): Sharing mode ('streamlit' or 'public')
129
- theme (str): Theme name ('streamlit' or None)
130
- **kwargs: Additional Plotly configuration options
131
132
Returns:
133
None
134
"""
135
136
def altair_chart(altair_chart, use_container_width=False, theme="streamlit"):
137
"""
138
Display a chart using the Altair library.
139
140
Parameters:
141
- altair_chart: Altair chart object
142
- use_container_width (bool): Use full container width
143
- theme (str): Theme name ('streamlit' or None)
144
145
Returns:
146
None
147
"""
148
149
def vega_lite_chart(data=None, spec=None, use_container_width=False, theme="streamlit", **kwargs):
150
"""
151
Display a chart using the Vega-Lite library.
152
153
Parameters:
154
- data: Chart data (DataFrame, dict, or None if data is in spec)
155
- spec (dict): Vega-Lite specification
156
- use_container_width (bool): Use full container width
157
- theme (str): Theme name ('streamlit' or None)
158
- **kwargs: Additional chart data or specification options
159
160
Returns:
161
None
162
"""
163
164
def pyplot(fig=None, clear_figure=None, use_container_width=True, **kwargs):
165
"""
166
Display a matplotlib.pyplot figure.
167
168
Parameters:
169
- fig: Matplotlib figure object (uses current figure if None)
170
- clear_figure (bool): Clear the figure after displaying
171
- use_container_width (bool): Use full container width
172
- **kwargs: Additional matplotlib configuration options
173
174
Returns:
175
None
176
"""
177
178
def bokeh_chart(figure, use_container_width=False):
179
"""
180
Display an interactive Bokeh chart.
181
182
Parameters:
183
- figure: Bokeh figure object
184
- use_container_width (bool): Use full container width
185
186
Returns:
187
None
188
"""
189
190
def pydeck_chart(pydeck_obj=None, use_container_width=False):
191
"""
192
Display a chart using the PyDeck library for 3D visualizations.
193
194
Parameters:
195
- pydeck_obj: PyDeck Deck object
196
- use_container_width (bool): Use full container width
197
198
Returns:
199
None
200
"""
201
202
def graphviz_chart(figure_or_dot, use_container_width=False):
203
"""
204
Display a graph using the Graphviz library.
205
206
Parameters:
207
- figure_or_dot: Graphviz figure object or DOT string
208
- use_container_width (bool): Use full container width
209
210
Returns:
211
None
212
"""
213
```
214
215
## Usage Examples
216
217
### Built-in Charts
218
219
```python
220
import streamlit as st
221
import pandas as pd
222
import numpy as np
223
224
# Generate sample data
225
chart_data = pd.DataFrame({
226
'date': pd.date_range('2023-01-01', periods=30),
227
'sales': np.random.randint(100, 1000, 30),
228
'profit': np.random.randint(10, 100, 30),
229
'region': np.random.choice(['North', 'South', 'East', 'West'], 30)
230
})
231
232
# Line chart
233
st.subheader("Sales Trend")
234
st.line_chart(
235
chart_data,
236
x='date',
237
y='sales',
238
use_container_width=True
239
)
240
241
# Multiple series line chart
242
st.subheader("Sales vs Profit")
243
st.line_chart(
244
chart_data,
245
x='date',
246
y=['sales', 'profit'],
247
x_label="Date",
248
y_label="Amount ($)"
249
)
250
251
# Bar chart with color encoding
252
st.subheader("Sales by Region")
253
region_data = chart_data.groupby('region')['sales'].sum().reset_index()
254
st.bar_chart(
255
region_data,
256
x='region',
257
y='sales',
258
color='region'
259
)
260
261
# Scatter plot
262
st.subheader("Sales vs Profit Correlation")
263
st.scatter_chart(
264
chart_data,
265
x='sales',
266
y='profit',
267
color='region',
268
size='sales'
269
)
270
```
271
272
### Map Visualization
273
274
```python
275
# Sample location data
276
map_data = pd.DataFrame({
277
'latitude': [37.7749, 40.7128, 41.8781, 34.0522],
278
'longitude': [-122.4194, -74.0060, -87.6298, -118.2437],
279
'city': ['San Francisco', 'New York', 'Chicago', 'Los Angeles'],
280
'population': [883305, 8175133, 2695598, 3971883]
281
})
282
283
st.subheader("City Locations")
284
st.map(
285
map_data,
286
latitude='latitude',
287
longitude='longitude',
288
size='population',
289
zoom=3
290
)
291
```
292
293
### Matplotlib Integration
294
295
```python
296
import matplotlib.pyplot as plt
297
298
# Create matplotlib figure
299
fig, ax = plt.subplots(figsize=(10, 6))
300
ax.hist(np.random.randn(1000), bins=30, alpha=0.7)
301
ax.set_title('Distribution of Random Values')
302
ax.set_xlabel('Value')
303
ax.set_ylabel('Frequency')
304
305
st.subheader("Matplotlib Histogram")
306
st.pyplot(fig)
307
```
308
309
### Plotly Integration
310
311
```python
312
import plotly.express as px
313
import plotly.graph_objects as go
314
315
# Simple Plotly chart
316
fig = px.scatter(
317
chart_data,
318
x='sales',
319
y='profit',
320
color='region',
321
size='sales',
322
title='Sales vs Profit by Region'
323
)
324
325
st.subheader("Interactive Plotly Scatter")
326
st.plotly_chart(fig, use_container_width=True)
327
328
# Advanced Plotly chart with multiple traces
329
fig = go.Figure()
330
fig.add_trace(go.Scatter(
331
x=chart_data['date'],
332
y=chart_data['sales'],
333
mode='lines+markers',
334
name='Sales',
335
line=dict(color='blue')
336
))
337
fig.add_trace(go.Scatter(
338
x=chart_data['date'],
339
y=chart_data['profit'],
340
mode='lines+markers',
341
name='Profit',
342
line=dict(color='red')
343
))
344
fig.update_layout(title='Sales and Profit Over Time')
345
346
st.subheader("Multi-trace Plotly Chart")
347
st.plotly_chart(fig, use_container_width=True)
348
```
349
350
### Altair Integration
351
352
```python
353
import altair as alt
354
355
# Create Altair chart
356
chart = alt.Chart(chart_data).mark_circle(size=100).encode(
357
x='sales:Q',
358
y='profit:Q',
359
color='region:N',
360
tooltip=['date:T', 'sales:Q', 'profit:Q', 'region:N']
361
).interactive()
362
363
st.subheader("Interactive Altair Chart")
364
st.altair_chart(chart, use_container_width=True)
365
```
366
367
### Advanced Visualization with PyDeck
368
369
```python
370
import pydeck as pdk
371
372
# 3D visualization with PyDeck
373
layer = pdk.Layer(
374
'ScatterplotLayer',
375
data=map_data,
376
get_position=['longitude', 'latitude'],
377
get_radius='population',
378
radius_scale=0.0001,
379
get_color=[255, 140, 0],
380
elevation_scale=4,
381
elevation_range=[0, 1000],
382
pickable=True,
383
extruded=True,
384
)
385
386
view_state = pdk.ViewState(
387
latitude=39.8283,
388
longitude=-98.5795,
389
zoom=3,
390
pitch=50,
391
)
392
393
deck = pdk.Deck(
394
layers=[layer],
395
initial_view_state=view_state,
396
tooltip={'text': '{city}\nPopulation: {population}'}
397
)
398
399
st.subheader("3D City Population Visualization")
400
st.pydeck_chart(deck)
401
```
402
403
### Vega-Lite Specification
404
405
```python
406
# Custom Vega-Lite specification
407
spec = {
408
"mark": "bar",
409
"encoding": {
410
"x": {"field": "region", "type": "nominal"},
411
"y": {"field": "sales", "type": "quantitative", "aggregate": "mean"},
412
"color": {"field": "region", "type": "nominal"}
413
}
414
}
415
416
st.subheader("Custom Vega-Lite Chart")
417
st.vega_lite_chart(chart_data, spec, use_container_width=True)
418
```
419
420
### Chart Theming and Customization
421
422
```python
423
# Plotly chart with custom theme disabled
424
fig = px.bar(
425
region_data,
426
x='region',
427
y='sales',
428
title='Sales by Region (Default Plotly Theme)'
429
)
430
431
st.plotly_chart(fig, theme=None) # Use Plotly's default theme
432
433
# Altair chart with Streamlit theme
434
chart = alt.Chart(chart_data).mark_bar().encode(
435
x='region:N',
436
y='mean(sales):Q',
437
color='region:N'
438
)
439
440
st.altair_chart(chart, theme="streamlit") # Use Streamlit theme
441
```