- Spec files
pypi-streamlit
Describes: pkg:pypi/streamlit@1.16.x
- Description
- The fastest way to build and share data apps
- Author
- tessl
- Last updated
charts-media.md docs/
1# Charts and Media23Comprehensive 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.45## Capabilities67### Built-in Charts89Native Streamlit chart types that work directly with pandas DataFrames and array-like data.1011```python { .api }12def line_chart(data=None, x: str = None, y: str = None, width: int = None, height: int = None, use_container_width: bool = False) -> DeltaGenerator:13"""14Display a line chart.1516Parameters:17- data: pandas.DataFrame, dict, list, or array-like data18- 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 pixels21- height: Chart height in pixels22- use_container_width: Whether to use full container width23"""2425def area_chart(data=None, x: str = None, y: str = None, width: int = None, height: int = None, use_container_width: bool = False) -> DeltaGenerator:26"""27Display an area chart.2829Parameters:30- data: pandas.DataFrame, dict, list, or array-like data31- 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 pixels34- height: Chart height in pixels35- use_container_width: Whether to use full container width36"""3738def bar_chart(data=None, x: str = None, y: str = None, width: int = None, height: int = None, use_container_width: bool = False) -> DeltaGenerator:39"""40Display a bar chart.4142Parameters:43- data: pandas.DataFrame, dict, list, or array-like data44- 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 pixels47- height: Chart height in pixels48- use_container_width: Whether to use full container width49"""50```5152#### Usage Example5354```python55import streamlit as st56import pandas as pd57import numpy as np5859# Sample data60data = 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})6566# Line chart67st.subheader("Sales and Profit Over Time")68st.line_chart(data.set_index('date')[['sales', 'profit']])6970# Area chart71st.subheader("Revenue Composition")72area_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})77st.area_chart(area_data)7879# Bar chart80st.subheader("Monthly Performance")81monthly_data = pd.DataFrame({82'Month': ['Jan', 'Feb', 'Mar', 'Apr', 'May'],83'Revenue': [12000, 15000, 18000, 16000, 20000]84})85st.bar_chart(monthly_data.set_index('Month'))86```8788### Maps and Geographic Data8990Display geographic data with interactive maps.9192```python { .api }93def map(data=None, zoom: int = None, use_container_width: bool = False) -> DeltaGenerator:94"""95Display data points on an interactive map.9697Parameters: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 width101"""102```103104#### Usage Example105106```python107import streamlit as st108import pandas as pd109import numpy as np110111# Sample geographic data112map_data = pd.DataFrame({113'lat': np.random.randn(100) * 0.01 + 37.7749, # San Francisco area114'lon': np.random.randn(100) * 0.01 + -122.4194115})116117st.subheader("Location Data")118st.map(map_data)119120# Map with specific zoom121st.map(map_data, zoom=12)122```123124### Matplotlib Integration125126Display matplotlib figures and plots.127128```python { .api }129def pyplot(fig=None, clear_figure: bool = None, use_container_width: bool = False, **kwargs) -> DeltaGenerator:130"""131Display a matplotlib pyplot figure.132133Parameters:134- fig: matplotlib.figure.Figure object (uses plt.gcf() if None)135- clear_figure: Whether to clear the figure after displaying136- use_container_width: Whether to use full container width137- **kwargs: Additional arguments passed to st.image()138"""139```140141#### Usage Example142143```python144import streamlit as st145import matplotlib.pyplot as plt146import numpy as np147148# Create matplotlib figure149fig, ax = plt.subplots()150x = np.linspace(0, 10, 100)151y = np.sin(x)152ax.plot(x, y, 'b-', linewidth=2, label='sin(x)')153ax.set_xlabel('X values')154ax.set_ylabel('Y values')155ax.set_title('Sine Wave')156ax.legend()157ax.grid(True)158159# Display in Streamlit160st.pyplot(fig)161162# Or use current figure163plt.figure(figsize=(10, 6))164plt.scatter(np.random.randn(100), np.random.randn(100))165plt.title('Random Scatter Plot')166st.pyplot() # Uses current figure167```168169### Altair Charts170171Display Altair/Vega-Lite charts for advanced statistical visualizations.172173```python { .api }174def altair_chart(altair_chart, use_container_width: bool = False) -> DeltaGenerator:175"""176Display an Altair chart.177178Parameters:179- altair_chart: altair.Chart object180- use_container_width: Whether to use full container width181"""182183def vega_lite_chart(spec: dict, use_container_width: bool = False, **kwargs) -> DeltaGenerator:184"""185Display a Vega-Lite chart from specification.186187Parameters:188- spec: Vega-Lite specification dictionary189- use_container_width: Whether to use full container width190- **kwargs: Additional arguments191"""192```193194#### Usage Example195196```python197import streamlit as st198import altair as alt199import pandas as pd200import numpy as np201202# Sample data203data = pd.DataFrame({204'x': np.random.randn(100),205'y': np.random.randn(100),206'category': np.random.choice(['A', 'B', 'C'], 100)207})208209# Altair scatter plot210chart = alt.Chart(data).mark_circle(size=60).encode(211x='x:Q',212y='y:Q',213color='category:N',214tooltip=['x:Q', 'y:Q', 'category:N']215).interactive()216217st.altair_chart(chart, use_container_width=True)218219# Vega-Lite specification220vega_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}228229st.vega_lite_chart(vega_spec)230```231232### Plotly Charts233234Display interactive Plotly charts with zoom, pan, and hover capabilities.235236```python { .api }237def plotly_chart(figure_or_data, use_container_width: bool = False, sharing: str = "streamlit", **kwargs) -> DeltaGenerator:238"""239Display a Plotly chart.240241Parameters:242- figure_or_data: plotly.graph_objects.Figure or plotly data structure243- use_container_width: Whether to use full container width244- sharing: Sharing mode for Plotly ("streamlit", "public", "private")245- **kwargs: Additional arguments passed to plotly246"""247```248249#### Usage Example250251```python252import streamlit as st253import plotly.graph_objects as go254import plotly.express as px255import pandas as pd256import numpy as np257258# Sample data259df = 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})265266# Plotly Express scatter plot267fig = px.scatter(268df, x='x', y='y',269size='size', color='category',270title='Interactive Scatter Plot',271hover_data=['size']272)273st.plotly_chart(fig, use_container_width=True)274275# Plotly Graph Objects276fig = go.Figure()277fig.add_trace(go.Scatter(278x=df['x'], y=df['y'],279mode='markers',280marker=dict(size=df['size'], color=df['size'], colorscale='Viridis'),281text=df['category'],282hovertemplate='X: %{x}<br>Y: %{y}<br>Size: %{marker.size}<extra></extra>'283))284fig.update_layout(title='Custom Plotly Chart')285st.plotly_chart(fig)286```287288### Other Chart Libraries289290Support for additional visualization libraries.291292```python { .api }293def bokeh_chart(figure, use_container_width: bool = False) -> DeltaGenerator:294"""295Display a Bokeh chart.296297Parameters:298- figure: bokeh.plotting.Figure object299- use_container_width: Whether to use full container width300"""301302def pydeck_chart(pydeck_obj=None, use_container_width: bool = False) -> DeltaGenerator:303"""304Display a PyDeck (deck.gl) chart for 3D visualizations.305306Parameters:307- pydeck_obj: pydeck.Deck object308- use_container_width: Whether to use full container width309"""310311def graphviz_chart(figure_or_dot, use_container_width: bool = False) -> DeltaGenerator:312"""313Display a Graphviz chart for network/graph visualizations.314315Parameters:316- figure_or_dot: graphviz.Graph object or DOT string317- use_container_width: Whether to use full container width318"""319```320321#### Usage Example322323```python324import streamlit as st325326# Bokeh example327from bokeh.plotting import figure328p = figure(title="Simple Line Plot", x_axis_label='x', y_axis_label='y')329p.line([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], legend_label="Temp.", line_width=2)330st.bokeh_chart(p)331332# PyDeck 3D visualization example333import pydeck as pdk334data = pd.DataFrame({335'lat': [37.7749, 37.7849, 37.7949],336'lon': [-122.4194, -122.4094, -122.3994],337'elevation': [100, 200, 150]338})339340st.pydeck_chart(pdk.Deck(341map_style='mapbox://styles/mapbox/light-v9',342initial_view_state=pdk.ViewState(343latitude=37.7749,344longitude=-122.4194,345zoom=11,346pitch=50,347),348layers=[349pdk.Layer(350'HexagonLayer',351data=data,352get_position='[lon, lat]',353radius=200,354elevation_scale=4,355elevation_range=[0, 1000],356pickable=True,357extruded=True,358),359],360))361362# Graphviz example363import graphviz364dot = graphviz.Digraph()365dot.edge('A', 'B')366dot.edge('B', 'C')367dot.edge('A', 'C')368st.graphviz_chart(dot)369```370371### Images372373Display and manipulate image data from various sources.374375```python { .api }376def 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"""378Display an image or list of images.379380Parameters:381- image: Image data (PIL.Image, numpy.ndarray, BytesIO, str path, or URL)382- caption: Image caption text383- 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 range386- channels: Color channel format ("RGB", "BGR")387- output_format: Output format ("JPEG", "PNG", "auto")388"""389```390391#### Usage Example392393```python394import streamlit as st395from PIL import Image396import numpy as np397398# Display image from file399image = Image.open('path/to/image.jpg')400st.image(image, caption='Sample Image', width=300)401402# Display image from URL403st.image('https://example.com/image.jpg', caption='Image from URL')404405# Display numpy array as image406img_array = np.random.randint(0, 255, (100, 100, 3), dtype=np.uint8)407st.image(img_array, caption='Generated Image')408409# Multiple images in gallery410images = [image1, image2, image3]411captions = ['Image 1', 'Image 2', 'Image 3']412st.image(images, caption=captions, width=200)413414# Use column width415st.image(image, use_column_width=True)416```417418### Audio and Video419420Display audio and video content with built-in media players.421422```python { .api }423def audio(data, format: str = "audio/wav", start_time: int = 0) -> DeltaGenerator:424"""425Display an audio player.426427Parameters:428- data: Audio data (bytes, BytesIO, numpy.ndarray, or file path)429- format: Audio format MIME type430- start_time: Start time in seconds431"""432433def video(data, format: str = "video/mp4", start_time: int = 0) -> DeltaGenerator:434"""435Display a video player.436437Parameters:438- data: Video data (bytes, BytesIO, numpy.ndarray, or file path)439- format: Video format MIME type440- start_time: Start time in seconds441"""442```443444#### Usage Example445446```python447import streamlit as st448449# Audio player450audio_file = open('audio.wav', 'rb')451audio_bytes = audio_file.read()452st.audio(audio_bytes, format='audio/wav')453454# Video player455video_file = open('video.mp4', 'rb')456video_bytes = video_file.read()457st.video(video_bytes)458459# Video with custom start time460st.video('https://example.com/video.mp4', start_time=30)461462# Audio from numpy array (synthetic audio)463import numpy as np464sample_rate = 44100465duration = 2 # seconds466t = np.linspace(0, duration, int(sample_rate * duration))467frequency = 440 # A4 note468audio_data = np.sin(2 * np.pi * frequency * t)469st.audio(audio_data, sample_rate=sample_rate)470```471472## Chart Configuration and Styling473474Most chart functions support additional styling and configuration options:475476```python477# Chart with custom dimensions478st.line_chart(data, width=800, height=400)479480# Chart using full container width481st.plotly_chart(fig, use_container_width=True)482483# Combining charts in layouts484col1, col2 = st.columns(2)485with col1:486st.line_chart(data1)487with col2:488st.bar_chart(data2)489```490491## Performance Tips492493- Use built-in charts for simple visualizations (faster rendering)494- Use Plotly for interactive features and complex charts495- Use `use_container_width=True` for responsive layouts496- Consider caching expensive chart generation with `@st.cache_data`