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

data-display.md docs/

1
# Data Display
2
3
Advanced data display components for presenting and editing tabular data and metrics. These components provide rich interactions for data exploration and manipulation.
4
5
## Capabilities
6
7
### Interactive DataFrames
8
9
Display and interact with tabular data using enhanced dataframe components.
10
11
```python { .api }
12
def dataframe(data=None, width=None, height=None, use_container_width=False, hide_index=None, column_order=None, column_config=None, selection_mode="single-row", on_select="rerun", key=None):
13
"""
14
Display a dataframe as an interactive table.
15
16
Parameters:
17
- data: DataFrame, array-like, or dict to display
18
- width (int): Table width in pixels
19
- height (int): Table height in pixels
20
- use_container_width (bool): Use full container width
21
- hide_index (bool): Hide row indices
22
- column_order (list): Custom column order
23
- column_config (dict): Column configuration mapping
24
- selection_mode (str): Row selection mode ('single-row', 'multi-row', 'single-column', 'multi-column', or 'disabled')
25
- on_select (str): Behavior on selection ('rerun' or 'ignore')
26
- key (str): Unique key for the widget
27
28
Returns:
29
DataFrame selection information
30
"""
31
32
def data_editor(data, width=None, height=None, use_container_width=False, hide_index=None, column_order=None, column_config=None, num_rows="fixed", disabled=False, key=None, on_change=None, args=None, kwargs=None):
33
"""
34
Display an editable data table.
35
36
Parameters:
37
- data: DataFrame, array-like, or dict to edit
38
- width (int): Table width in pixels
39
- height (int): Table height in pixels
40
- use_container_width (bool): Use full container width
41
- hide_index (bool): Hide row indices
42
- column_order (list): Custom column order
43
- column_config (dict): Column configuration mapping
44
- num_rows (str): Row management ('fixed', 'dynamic')
45
- disabled (bool): Disable editing
46
- key (str): Unique key for the widget
47
- on_change (callable): Function to call when data changes
48
- args (tuple): Arguments to pass to on_change function
49
- kwargs (dict): Keyword arguments to pass to on_change function
50
51
Returns:
52
DataFrame: Edited data
53
"""
54
```
55
56
### Static Tables
57
58
Display read-only tabular data with simple formatting.
59
60
```python { .api }
61
def table(data=None):
62
"""
63
Display a static table.
64
65
Parameters:
66
- data: DataFrame, array-like, or dict to display as table
67
68
Returns:
69
None
70
"""
71
```
72
73
### Metrics Display
74
75
Display key performance indicators and metrics with delta comparisons.
76
77
```python { .api }
78
def metric(label, value, delta=None, delta_color="normal", help=None, label_visibility="visible"):
79
"""
80
Display a metric in large, prominent formatting.
81
82
Parameters:
83
- label (str): Metric label
84
- value: Metric value (number or string)
85
- delta: Change in metric value (number or string)
86
- delta_color (str): Color for delta ('normal', 'inverse', or 'off')
87
- help (str): Optional tooltip text
88
- label_visibility (str): Label visibility ('visible', 'hidden', 'collapsed')
89
90
Returns:
91
None
92
"""
93
```
94
95
## Column Configuration
96
97
Configure how columns are displayed and edited in dataframes and data editors.
98
99
### Column Configuration Classes
100
101
```python { .api }
102
# Base column configuration
103
class Column:
104
"""Base column configuration class."""
105
def __init__(self, label=None, width=None, help=None, disabled=None, required=None):
106
"""
107
Parameters:
108
- label (str): Column display name
109
- width (str): Column width ('small', 'medium', 'large', or pixel value)
110
- help (str): Help text for column header
111
- disabled (bool): Disable editing for this column
112
- required (bool): Mark column as required
113
"""
114
115
# Text column configuration
116
class TextColumn(Column):
117
"""Text column configuration with validation."""
118
def __init__(self, max_chars=None, validate=None, **kwargs):
119
"""
120
Parameters:
121
- max_chars (int): Maximum character count
122
- validate (str or callable): Validation pattern or function
123
"""
124
125
# Number column configuration
126
class NumberColumn(Column):
127
"""Numeric column configuration with formatting."""
128
def __init__(self, min_value=None, max_value=None, step=None, format=None, **kwargs):
129
"""
130
Parameters:
131
- min_value (float): Minimum allowed value
132
- max_value (float): Maximum allowed value
133
- step (float): Step size for increments
134
- format (str): Number format string
135
"""
136
137
# Checkbox column configuration
138
class CheckboxColumn(Column):
139
"""Boolean checkbox column configuration."""
140
pass
141
142
# Selectbox column configuration
143
class SelectboxColumn(Column):
144
"""Dropdown selection column configuration."""
145
def __init__(self, options, **kwargs):
146
"""
147
Parameters:
148
- options (list): Available options for selection
149
"""
150
151
# Date and time column configurations
152
class DateColumn(Column):
153
"""Date column configuration."""
154
def __init__(self, min_value=None, max_value=None, format="YYYY-MM-DD", step=1, **kwargs):
155
"""
156
Parameters:
157
- min_value (date): Minimum date
158
- max_value (date): Maximum date
159
- format (str): Date format string
160
- step (int): Step size in days
161
"""
162
163
class TimeColumn(Column):
164
"""Time column configuration."""
165
def __init__(self, min_value=None, max_value=None, format="HH:mm", step=60, **kwargs):
166
"""
167
Parameters:
168
- min_value (time): Minimum time
169
- max_value (time): Maximum time
170
- format (str): Time format string
171
- step (int): Step size in seconds
172
"""
173
174
class DatetimeColumn(Column):
175
"""Datetime column configuration."""
176
def __init__(self, min_value=None, max_value=None, format="YYYY-MM-DD HH:mm", step=60, timezone=None, **kwargs):
177
"""
178
Parameters:
179
- min_value (datetime): Minimum datetime
180
- max_value (datetime): Maximum datetime
181
- format (str): Datetime format string
182
- step (int): Step size in seconds
183
- timezone (str): Timezone name
184
"""
185
186
# Link column configuration
187
class LinkColumn(Column):
188
"""URL link column configuration."""
189
def __init__(self, validate=None, max_chars=None, display_text=None, **kwargs):
190
"""
191
Parameters:
192
- validate (str or callable): URL validation pattern or function
193
- max_chars (int): Maximum character count
194
- display_text (str or callable): Custom display text or function
195
"""
196
197
# List column configuration
198
class ListColumn(Column):
199
"""List/array column configuration."""
200
pass
201
202
# Image column configuration
203
class ImageColumn(Column):
204
"""Image display column configuration."""
205
pass
206
207
# Chart column configurations
208
class LineChartColumn(Column):
209
"""Line chart column configuration."""
210
def __init__(self, y_min=None, y_max=None, **kwargs):
211
"""
212
Parameters:
213
- y_min (float): Minimum Y-axis value
214
- y_max (float): Maximum Y-axis value
215
"""
216
217
class BarChartColumn(Column):
218
"""Bar chart column configuration."""
219
def __init__(self, y_min=None, y_max=None, **kwargs):
220
"""
221
Parameters:
222
- y_min (float): Minimum Y-axis value
223
- y_max (float): Maximum Y-axis value
224
"""
225
226
class AreaChartColumn(Column):
227
"""Area chart column configuration."""
228
def __init__(self, y_min=None, y_max=None, **kwargs):
229
"""
230
Parameters:
231
- y_min (float): Minimum Y-axis value
232
- y_max (float): Maximum Y-axis value
233
"""
234
235
# Progress column configuration
236
class ProgressColumn(Column):
237
"""Progress bar column configuration."""
238
def __init__(self, min_value=0, max_value=100, format=None, **kwargs):
239
"""
240
Parameters:
241
- min_value (float): Minimum progress value
242
- max_value (float): Maximum progress value
243
- format (str): Progress display format
244
"""
245
246
# JSON column configuration
247
class JsonColumn(Column):
248
"""JSON data column configuration."""
249
pass
250
```
251
252
## Usage Examples
253
254
### Basic Data Display
255
256
```python
257
import streamlit as st
258
import pandas as pd
259
import numpy as np
260
261
# Create sample data
262
data = pd.DataFrame({
263
'Name': ['Alice', 'Bob', 'Charlie', 'David'],
264
'Age': [25, 30, 35, 28],
265
'Salary': [50000, 60000, 70000, 55000],
266
'Active': [True, True, False, True]
267
})
268
269
# Display as interactive dataframe
270
st.subheader("Interactive DataFrame")
271
st.dataframe(data, use_container_width=True)
272
273
# Display as static table
274
st.subheader("Static Table")
275
st.table(data.head(2))
276
```
277
278
### Advanced DataFrame Configuration
279
280
```python
281
# Configure columns with specific types and formatting
282
column_config = {
283
"Name": st.column_config.TextColumn(
284
"Employee Name",
285
help="Full name of employee",
286
max_chars=50,
287
required=True
288
),
289
"Age": st.column_config.NumberColumn(
290
"Age (years)",
291
help="Employee age in years",
292
min_value=18,
293
max_value=65,
294
step=1,
295
format="%d"
296
),
297
"Salary": st.column_config.NumberColumn(
298
"Annual Salary",
299
help="Annual salary in USD",
300
min_value=0,
301
format="$%d"
302
),
303
"Active": st.column_config.CheckboxColumn(
304
"Currently Active",
305
help="Whether employee is currently active"
306
)
307
}
308
309
# Display with custom column configuration
310
edited_df = st.data_editor(
311
data,
312
column_config=column_config,
313
num_rows="dynamic",
314
use_container_width=True
315
)
316
317
st.write("Edited data:", edited_df)
318
```
319
320
### Metrics Dashboard
321
322
```python
323
import random
324
325
# Display key metrics with deltas
326
col1, col2, col3, col4 = st.columns(4)
327
328
with col1:
329
st.metric(
330
label="Revenue",
331
value="$125,000",
332
delta="$12,000",
333
help="Monthly revenue with change from last month"
334
)
335
336
with col2:
337
st.metric(
338
label="Users",
339
value="2,847",
340
delta="-15",
341
delta_color="inverse"
342
)
343
344
with col3:
345
st.metric(
346
label="Conversion Rate",
347
value="3.2%",
348
delta="0.8%"
349
)
350
351
with col4:
352
st.metric(
353
label="Churn Rate",
354
value="2.1%",
355
delta="-0.3%",
356
delta_color="inverse"
357
)
358
```
359
360
### Data Editor with Row Management
361
362
```python
363
# Sample product data
364
products = pd.DataFrame({
365
'Product': ['Widget A', 'Widget B', 'Widget C'],
366
'Price': [10.99, 15.99, 8.99],
367
'In Stock': [True, False, True],
368
'Category': ['Electronics', 'Home', 'Electronics']
369
})
370
371
# Configure with selectbox for categories
372
config = {
373
'Category': st.column_config.SelectboxColumn(
374
'Product Category',
375
options=['Electronics', 'Home', 'Clothing', 'Books'],
376
required=True
377
),
378
'Price': st.column_config.NumberColumn(
379
'Price ($)',
380
min_value=0,
381
format='$%.2f'
382
)
383
}
384
385
# Editable table with dynamic rows
386
edited_products = st.data_editor(
387
products,
388
column_config=config,
389
num_rows="dynamic", # Allow adding/removing rows
390
key="product_editor"
391
)
392
393
# Show summary
394
st.write(f"Total products: {len(edited_products)}")
395
st.write(f"Total value: ${edited_products['Price'].sum():.2f}")
396
```
397
398
### Selection Handling
399
400
```python
401
# DataFrame with selection handling
402
selection = st.dataframe(
403
data,
404
selection_mode="multi-row",
405
on_select="rerun",
406
key="data_selection"
407
)
408
409
if selection.selection.rows:
410
selected_data = data.iloc[selection.selection.rows]
411
st.write("Selected rows:")
412
st.dataframe(selected_data)
413
else:
414
st.write("No rows selected")
415
```