pypi-streamlit

Description
The fastest way to build and share data apps
Author
tessl
Last updated

How to use

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

charts-media.md docs/

1
# Charts and Media
2
3
Comprehensive visualization and media display capabilities. Streamlit provides built-in chart types for quick data visualization, integration with popular plotting libraries, and multimedia content rendering for images, audio, and video.
4
5
## Capabilities
6
7
### Built-in Charts
8
9
Native Streamlit chart types that work directly with pandas DataFrames and array-like data.
10
11
```python { .api }
12
def line_chart(data=None, x: str = None, y: str = None, width: int = None, height: int = None, use_container_width: bool = False) -> DeltaGenerator:
13
"""
14
Display a line chart.
15
16
Parameters:
17
- data: pandas.DataFrame, dict, list, or array-like data
18
- x: Column name for x-axis (optional)
19
- y: Column name or list of column names for y-axis (optional)
20
- width: Chart width in pixels
21
- height: Chart height in pixels
22
- use_container_width: Whether to use full container width
23
"""
24
25
def area_chart(data=None, x: str = None, y: str = None, width: int = None, height: int = None, use_container_width: bool = False) -> DeltaGenerator:
26
"""
27
Display an area chart.
28
29
Parameters:
30
- data: pandas.DataFrame, dict, list, or array-like data
31
- x: Column name for x-axis (optional)
32
- y: Column name or list of column names for y-axis (optional)
33
- width: Chart width in pixels
34
- height: Chart height in pixels
35
- use_container_width: Whether to use full container width
36
"""
37
38
def bar_chart(data=None, x: str = None, y: str = None, width: int = None, height: int = None, use_container_width: bool = False) -> DeltaGenerator:
39
"""
40
Display a bar chart.
41
42
Parameters:
43
- data: pandas.DataFrame, dict, list, or array-like data
44
- x: Column name for x-axis (optional)
45
- y: Column name or list of column names for y-axis (optional)
46
- width: Chart width in pixels
47
- height: Chart height in pixels
48
- use_container_width: Whether to use full container width
49
"""
50
```
51
52
#### Usage Example
53
54
```python
55
import streamlit as st
56
import pandas as pd
57
import numpy as np
58
59
# Sample data
60
data = pd.DataFrame({
61
'date': pd.date_range('2024-01-01', periods=30, freq='D'),
62
'sales': np.random.randint(100, 1000, 30),
63
'profit': np.random.randint(50, 400, 30)
64
})
65
66
# Line chart
67
st.subheader("Sales and Profit Over Time")
68
st.line_chart(data.set_index('date')[['sales', 'profit']])
69
70
# Area chart
71
st.subheader("Revenue Composition")
72
area_data = pd.DataFrame({
73
'Product A': np.random.randint(50, 200, 20),
74
'Product B': np.random.randint(30, 150, 20),
75
'Product C': np.random.randint(20, 100, 20)
76
})
77
st.area_chart(area_data)
78
79
# Bar chart
80
st.subheader("Monthly Performance")
81
monthly_data = pd.DataFrame({
82
'Month': ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
83
'Revenue': [12000, 15000, 18000, 16000, 20000]
84
})
85
st.bar_chart(monthly_data.set_index('Month'))
86
```
87
88
### Maps and Geographic Data
89
90
Display geographic data with interactive maps.
91
92
```python { .api }
93
def map(data=None, zoom: int = None, use_container_width: bool = False) -> DeltaGenerator:
94
"""
95
Display data points on an interactive map.
96
97
Parameters:
98
- data: pandas.DataFrame with 'lat' and 'lon' columns, or 'latitude'/'longitude'
99
- zoom: Map zoom level (1-20)
100
- use_container_width: Whether to use full container width
101
"""
102
```
103
104
#### Usage Example
105
106
```python
107
import streamlit as st
108
import pandas as pd
109
import numpy as np
110
111
# Sample geographic data
112
map_data = pd.DataFrame({
113
'lat': np.random.randn(100) * 0.01 + 37.7749, # San Francisco area
114
'lon': np.random.randn(100) * 0.01 + -122.4194
115
})
116
117
st.subheader("Location Data")
118
st.map(map_data)
119
120
# Map with specific zoom
121
st.map(map_data, zoom=12)
122
```
123
124
### Matplotlib Integration
125
126
Display matplotlib figures and plots.
127
128
```python { .api }
129
def pyplot(fig=None, clear_figure: bool = None, use_container_width: bool = False, **kwargs) -> DeltaGenerator:
130
"""
131
Display a matplotlib pyplot figure.
132
133
Parameters:
134
- fig: matplotlib.figure.Figure object (uses plt.gcf() if None)
135
- clear_figure: Whether to clear the figure after displaying
136
- use_container_width: Whether to use full container width
137
- **kwargs: Additional arguments passed to st.image()
138
"""
139
```
140
141
#### Usage Example
142
143
```python
144
import streamlit as st
145
import matplotlib.pyplot as plt
146
import numpy as np
147
148
# Create matplotlib figure
149
fig, ax = plt.subplots()
150
x = np.linspace(0, 10, 100)
151
y = np.sin(x)
152
ax.plot(x, y, 'b-', linewidth=2, label='sin(x)')
153
ax.set_xlabel('X values')
154
ax.set_ylabel('Y values')
155
ax.set_title('Sine Wave')
156
ax.legend()
157
ax.grid(True)
158
159
# Display in Streamlit
160
st.pyplot(fig)
161
162
# Or use current figure
163
plt.figure(figsize=(10, 6))
164
plt.scatter(np.random.randn(100), np.random.randn(100))
165
plt.title('Random Scatter Plot')
166
st.pyplot() # Uses current figure
167
```
168
169
### Altair Charts
170
171
Display Altair/Vega-Lite charts for advanced statistical visualizations.
172
173
```python { .api }
174
def altair_chart(altair_chart, use_container_width: bool = False) -> DeltaGenerator:
175
"""
176
Display an Altair chart.
177
178
Parameters:
179
- altair_chart: altair.Chart object
180
- use_container_width: Whether to use full container width
181
"""
182
183
def vega_lite_chart(spec: dict, use_container_width: bool = False, **kwargs) -> DeltaGenerator:
184
"""
185
Display a Vega-Lite chart from specification.
186
187
Parameters:
188
- spec: Vega-Lite specification dictionary
189
- use_container_width: Whether to use full container width
190
- **kwargs: Additional arguments
191
"""
192
```
193
194
#### Usage Example
195
196
```python
197
import streamlit as st
198
import altair as alt
199
import pandas as pd
200
import numpy as np
201
202
# Sample data
203
data = pd.DataFrame({
204
'x': np.random.randn(100),
205
'y': np.random.randn(100),
206
'category': np.random.choice(['A', 'B', 'C'], 100)
207
})
208
209
# Altair scatter plot
210
chart = alt.Chart(data).mark_circle(size=60).encode(
211
x='x:Q',
212
y='y:Q',
213
color='category:N',
214
tooltip=['x:Q', 'y:Q', 'category:N']
215
).interactive()
216
217
st.altair_chart(chart, use_container_width=True)
218
219
# Vega-Lite specification
220
vega_spec = {
221
"mark": "bar",
222
"encoding": {
223
"x": {"field": "category", "type": "ordinal"},
224
"y": {"aggregate": "count", "type": "quantitative"}
225
},
226
"data": {"values": data.to_dict('records')}
227
}
228
229
st.vega_lite_chart(vega_spec)
230
```
231
232
### Plotly Charts
233
234
Display interactive Plotly charts with zoom, pan, and hover capabilities.
235
236
```python { .api }
237
def plotly_chart(figure_or_data, use_container_width: bool = False, sharing: str = "streamlit", **kwargs) -> DeltaGenerator:
238
"""
239
Display a Plotly chart.
240
241
Parameters:
242
- figure_or_data: plotly.graph_objects.Figure or plotly data structure
243
- use_container_width: Whether to use full container width
244
- sharing: Sharing mode for Plotly ("streamlit", "public", "private")
245
- **kwargs: Additional arguments passed to plotly
246
"""
247
```
248
249
#### Usage Example
250
251
```python
252
import streamlit as st
253
import plotly.graph_objects as go
254
import plotly.express as px
255
import pandas as pd
256
import numpy as np
257
258
# Sample data
259
df = pd.DataFrame({
260
'x': np.random.randn(100),
261
'y': np.random.randn(100),
262
'size': np.random.randint(10, 50, 100),
263
'category': np.random.choice(['Group 1', 'Group 2', 'Group 3'], 100)
264
})
265
266
# Plotly Express scatter plot
267
fig = px.scatter(
268
df, x='x', y='y',
269
size='size', color='category',
270
title='Interactive Scatter Plot',
271
hover_data=['size']
272
)
273
st.plotly_chart(fig, use_container_width=True)
274
275
# Plotly Graph Objects
276
fig = go.Figure()
277
fig.add_trace(go.Scatter(
278
x=df['x'], y=df['y'],
279
mode='markers',
280
marker=dict(size=df['size'], color=df['size'], colorscale='Viridis'),
281
text=df['category'],
282
hovertemplate='X: %{x}<br>Y: %{y}<br>Size: %{marker.size}<extra></extra>'
283
))
284
fig.update_layout(title='Custom Plotly Chart')
285
st.plotly_chart(fig)
286
```
287
288
### Other Chart Libraries
289
290
Support for additional visualization libraries.
291
292
```python { .api }
293
def bokeh_chart(figure, use_container_width: bool = False) -> DeltaGenerator:
294
"""
295
Display a Bokeh chart.
296
297
Parameters:
298
- figure: bokeh.plotting.Figure object
299
- use_container_width: Whether to use full container width
300
"""
301
302
def pydeck_chart(pydeck_obj=None, use_container_width: bool = False) -> DeltaGenerator:
303
"""
304
Display a PyDeck (deck.gl) chart for 3D visualizations.
305
306
Parameters:
307
- pydeck_obj: pydeck.Deck object
308
- use_container_width: Whether to use full container width
309
"""
310
311
def graphviz_chart(figure_or_dot, use_container_width: bool = False) -> DeltaGenerator:
312
"""
313
Display a Graphviz chart for network/graph visualizations.
314
315
Parameters:
316
- figure_or_dot: graphviz.Graph object or DOT string
317
- use_container_width: Whether to use full container width
318
"""
319
```
320
321
#### Usage Example
322
323
```python
324
import streamlit as st
325
326
# Bokeh example
327
from bokeh.plotting import figure
328
p = figure(title="Simple Line Plot", x_axis_label='x', y_axis_label='y')
329
p.line([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], legend_label="Temp.", line_width=2)
330
st.bokeh_chart(p)
331
332
# PyDeck 3D visualization example
333
import pydeck as pdk
334
data = pd.DataFrame({
335
'lat': [37.7749, 37.7849, 37.7949],
336
'lon': [-122.4194, -122.4094, -122.3994],
337
'elevation': [100, 200, 150]
338
})
339
340
st.pydeck_chart(pdk.Deck(
341
map_style='mapbox://styles/mapbox/light-v9',
342
initial_view_state=pdk.ViewState(
343
latitude=37.7749,
344
longitude=-122.4194,
345
zoom=11,
346
pitch=50,
347
),
348
layers=[
349
pdk.Layer(
350
'HexagonLayer',
351
data=data,
352
get_position='[lon, lat]',
353
radius=200,
354
elevation_scale=4,
355
elevation_range=[0, 1000],
356
pickable=True,
357
extruded=True,
358
),
359
],
360
))
361
362
# Graphviz example
363
import graphviz
364
dot = graphviz.Digraph()
365
dot.edge('A', 'B')
366
dot.edge('B', 'C')
367
dot.edge('A', 'C')
368
st.graphviz_chart(dot)
369
```
370
371
### Images
372
373
Display and manipulate image data from various sources.
374
375
```python { .api }
376
def image(image, caption: str = None, width: int = None, use_column_width: str = None, clamp: bool = False, channels: str = "RGB", output_format: str = "auto") -> DeltaGenerator:
377
"""
378
Display an image or list of images.
379
380
Parameters:
381
- image: Image data (PIL.Image, numpy.ndarray, BytesIO, str path, or URL)
382
- caption: Image caption text
383
- width: Image width in pixels (None for original size)
384
- use_column_width: Whether to use column width ("auto", "always", "never")
385
- clamp: Whether to clamp image values to valid range
386
- channels: Color channel format ("RGB", "BGR")
387
- output_format: Output format ("JPEG", "PNG", "auto")
388
"""
389
```
390
391
#### Usage Example
392
393
```python
394
import streamlit as st
395
from PIL import Image
396
import numpy as np
397
398
# Display image from file
399
image = Image.open('path/to/image.jpg')
400
st.image(image, caption='Sample Image', width=300)
401
402
# Display image from URL
403
st.image('https://example.com/image.jpg', caption='Image from URL')
404
405
# Display numpy array as image
406
img_array = np.random.randint(0, 255, (100, 100, 3), dtype=np.uint8)
407
st.image(img_array, caption='Generated Image')
408
409
# Multiple images in gallery
410
images = [image1, image2, image3]
411
captions = ['Image 1', 'Image 2', 'Image 3']
412
st.image(images, caption=captions, width=200)
413
414
# Use column width
415
st.image(image, use_column_width=True)
416
```
417
418
### Audio and Video
419
420
Display audio and video content with built-in media players.
421
422
```python { .api }
423
def audio(data, format: str = "audio/wav", start_time: int = 0) -> DeltaGenerator:
424
"""
425
Display an audio player.
426
427
Parameters:
428
- data: Audio data (bytes, BytesIO, numpy.ndarray, or file path)
429
- format: Audio format MIME type
430
- start_time: Start time in seconds
431
"""
432
433
def video(data, format: str = "video/mp4", start_time: int = 0) -> DeltaGenerator:
434
"""
435
Display a video player.
436
437
Parameters:
438
- data: Video data (bytes, BytesIO, numpy.ndarray, or file path)
439
- format: Video format MIME type
440
- start_time: Start time in seconds
441
"""
442
```
443
444
#### Usage Example
445
446
```python
447
import streamlit as st
448
449
# Audio player
450
audio_file = open('audio.wav', 'rb')
451
audio_bytes = audio_file.read()
452
st.audio(audio_bytes, format='audio/wav')
453
454
# Video player
455
video_file = open('video.mp4', 'rb')
456
video_bytes = video_file.read()
457
st.video(video_bytes)
458
459
# Video with custom start time
460
st.video('https://example.com/video.mp4', start_time=30)
461
462
# Audio from numpy array (synthetic audio)
463
import numpy as np
464
sample_rate = 44100
465
duration = 2 # seconds
466
t = np.linspace(0, duration, int(sample_rate * duration))
467
frequency = 440 # A4 note
468
audio_data = np.sin(2 * np.pi * frequency * t)
469
st.audio(audio_data, sample_rate=sample_rate)
470
```
471
472
## Chart Configuration and Styling
473
474
Most chart functions support additional styling and configuration options:
475
476
```python
477
# Chart with custom dimensions
478
st.line_chart(data, width=800, height=400)
479
480
# Chart using full container width
481
st.plotly_chart(fig, use_container_width=True)
482
483
# Combining charts in layouts
484
col1, col2 = st.columns(2)
485
with col1:
486
st.line_chart(data1)
487
with col2:
488
st.bar_chart(data2)
489
```
490
491
## Performance Tips
492
493
- Use built-in charts for simple visualizations (faster rendering)
494
- Use Plotly for interactive features and complex charts
495
- Use `use_container_width=True` for responsive layouts
496
- Consider caching expensive chart generation with `@st.cache_data`