CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-streamlit

The fastest way to build and share data apps

Overview
Eval results
Files

charts-media.mddocs/

Charts and Media

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.

Capabilities

Built-in Charts

Native Streamlit chart types that work directly with pandas DataFrames and array-like data.

def line_chart(data=None, x: str = None, y: str = None, width: int = None, height: int = None, use_container_width: bool = False) -> DeltaGenerator:
    """
    Display a line chart.
    
    Parameters:
    - data: pandas.DataFrame, dict, list, or array-like data
    - x: Column name for x-axis (optional)
    - y: Column name or list of column names for y-axis (optional)
    - width: Chart width in pixels
    - height: Chart height in pixels
    - use_container_width: Whether to use full container width
    """

def area_chart(data=None, x: str = None, y: str = None, width: int = None, height: int = None, use_container_width: bool = False) -> DeltaGenerator:
    """
    Display an area chart.
    
    Parameters:
    - data: pandas.DataFrame, dict, list, or array-like data
    - x: Column name for x-axis (optional)
    - y: Column name or list of column names for y-axis (optional)
    - width: Chart width in pixels
    - height: Chart height in pixels
    - use_container_width: Whether to use full container width
    """

def bar_chart(data=None, x: str = None, y: str = None, width: int = None, height: int = None, use_container_width: bool = False) -> DeltaGenerator:
    """
    Display a bar chart.
    
    Parameters:
    - data: pandas.DataFrame, dict, list, or array-like data
    - x: Column name for x-axis (optional)
    - y: Column name or list of column names for y-axis (optional)
    - width: Chart width in pixels
    - height: Chart height in pixels
    - use_container_width: Whether to use full container width
    """

Usage Example

import streamlit as st
import pandas as pd
import numpy as np

# Sample data
data = pd.DataFrame({
    'date': pd.date_range('2024-01-01', periods=30, freq='D'),
    'sales': np.random.randint(100, 1000, 30),
    'profit': np.random.randint(50, 400, 30)
})

# Line chart
st.subheader("Sales and Profit Over Time")
st.line_chart(data.set_index('date')[['sales', 'profit']])

# Area chart
st.subheader("Revenue Composition")
area_data = pd.DataFrame({
    'Product A': np.random.randint(50, 200, 20),
    'Product B': np.random.randint(30, 150, 20),
    'Product C': np.random.randint(20, 100, 20)
})
st.area_chart(area_data)

# Bar chart
st.subheader("Monthly Performance")
monthly_data = pd.DataFrame({
    'Month': ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
    'Revenue': [12000, 15000, 18000, 16000, 20000]
})
st.bar_chart(monthly_data.set_index('Month'))

Maps and Geographic Data

Display geographic data with interactive maps.

def map(data=None, zoom: int = None, use_container_width: bool = False) -> DeltaGenerator:
    """
    Display data points on an interactive map.
    
    Parameters:
    - data: pandas.DataFrame with 'lat' and 'lon' columns, or 'latitude'/'longitude'
    - zoom: Map zoom level (1-20)
    - use_container_width: Whether to use full container width
    """

Usage Example

import streamlit as st
import pandas as pd
import numpy as np

# Sample geographic data
map_data = pd.DataFrame({
    'lat': np.random.randn(100) * 0.01 + 37.7749,  # San Francisco area
    'lon': np.random.randn(100) * 0.01 + -122.4194
})

st.subheader("Location Data")
st.map(map_data)

# Map with specific zoom
st.map(map_data, zoom=12)

Matplotlib Integration

Display matplotlib figures and plots.

def pyplot(fig=None, clear_figure: bool = None, use_container_width: bool = False, **kwargs) -> DeltaGenerator:
    """
    Display a matplotlib pyplot figure.
    
    Parameters:
    - fig: matplotlib.figure.Figure object (uses plt.gcf() if None)
    - clear_figure: Whether to clear the figure after displaying
    - use_container_width: Whether to use full container width
    - **kwargs: Additional arguments passed to st.image()
    """

Usage Example

import streamlit as st
import matplotlib.pyplot as plt
import numpy as np

# Create matplotlib figure
fig, ax = plt.subplots()
x = np.linspace(0, 10, 100)
y = np.sin(x)
ax.plot(x, y, 'b-', linewidth=2, label='sin(x)')
ax.set_xlabel('X values')
ax.set_ylabel('Y values')
ax.set_title('Sine Wave')
ax.legend()
ax.grid(True)

# Display in Streamlit
st.pyplot(fig)

# Or use current figure
plt.figure(figsize=(10, 6))
plt.scatter(np.random.randn(100), np.random.randn(100))
plt.title('Random Scatter Plot')
st.pyplot()  # Uses current figure

Altair Charts

Display Altair/Vega-Lite charts for advanced statistical visualizations.

def altair_chart(altair_chart, use_container_width: bool = False) -> DeltaGenerator:
    """
    Display an Altair chart.
    
    Parameters:
    - altair_chart: altair.Chart object
    - use_container_width: Whether to use full container width
    """

def vega_lite_chart(spec: dict, use_container_width: bool = False, **kwargs) -> DeltaGenerator:
    """
    Display a Vega-Lite chart from specification.
    
    Parameters:
    - spec: Vega-Lite specification dictionary
    - use_container_width: Whether to use full container width
    - **kwargs: Additional arguments
    """

Usage Example

import streamlit as st
import altair as alt
import pandas as pd
import numpy as np

# Sample data
data = pd.DataFrame({
    'x': np.random.randn(100),
    'y': np.random.randn(100),
    'category': np.random.choice(['A', 'B', 'C'], 100)
})

# Altair scatter plot
chart = alt.Chart(data).mark_circle(size=60).encode(
    x='x:Q',
    y='y:Q',
    color='category:N',
    tooltip=['x:Q', 'y:Q', 'category:N']
).interactive()

st.altair_chart(chart, use_container_width=True)

# Vega-Lite specification
vega_spec = {
    "mark": "bar",
    "encoding": {
        "x": {"field": "category", "type": "ordinal"},
        "y": {"aggregate": "count", "type": "quantitative"}
    },
    "data": {"values": data.to_dict('records')}
}

st.vega_lite_chart(vega_spec)

Plotly Charts

Display interactive Plotly charts with zoom, pan, and hover capabilities.

def plotly_chart(figure_or_data, use_container_width: bool = False, sharing: str = "streamlit", **kwargs) -> DeltaGenerator:
    """
    Display a Plotly chart.
    
    Parameters:
    - figure_or_data: plotly.graph_objects.Figure or plotly data structure
    - use_container_width: Whether to use full container width
    - sharing: Sharing mode for Plotly ("streamlit", "public", "private")
    - **kwargs: Additional arguments passed to plotly
    """

Usage Example

import streamlit as st
import plotly.graph_objects as go
import plotly.express as px
import pandas as pd
import numpy as np

# Sample data
df = pd.DataFrame({
    'x': np.random.randn(100),
    'y': np.random.randn(100),
    'size': np.random.randint(10, 50, 100),
    'category': np.random.choice(['Group 1', 'Group 2', 'Group 3'], 100)
})

# Plotly Express scatter plot
fig = px.scatter(
    df, x='x', y='y', 
    size='size', color='category',
    title='Interactive Scatter Plot',
    hover_data=['size']
)
st.plotly_chart(fig, use_container_width=True)

# Plotly Graph Objects
fig = go.Figure()
fig.add_trace(go.Scatter(
    x=df['x'], y=df['y'],
    mode='markers',
    marker=dict(size=df['size'], color=df['size'], colorscale='Viridis'),
    text=df['category'],
    hovertemplate='X: %{x}<br>Y: %{y}<br>Size: %{marker.size}<extra></extra>'
))
fig.update_layout(title='Custom Plotly Chart')
st.plotly_chart(fig)

Other Chart Libraries

Support for additional visualization libraries.

def bokeh_chart(figure, use_container_width: bool = False) -> DeltaGenerator:
    """
    Display a Bokeh chart.
    
    Parameters:
    - figure: bokeh.plotting.Figure object
    - use_container_width: Whether to use full container width
    """

def pydeck_chart(pydeck_obj=None, use_container_width: bool = False) -> DeltaGenerator:
    """
    Display a PyDeck (deck.gl) chart for 3D visualizations.
    
    Parameters:
    - pydeck_obj: pydeck.Deck object
    - use_container_width: Whether to use full container width
    """

def graphviz_chart(figure_or_dot, use_container_width: bool = False) -> DeltaGenerator:
    """
    Display a Graphviz chart for network/graph visualizations.
    
    Parameters:
    - figure_or_dot: graphviz.Graph object or DOT string
    - use_container_width: Whether to use full container width
    """

Usage Example

import streamlit as st

# Bokeh example
from bokeh.plotting import figure
p = figure(title="Simple Line Plot", x_axis_label='x', y_axis_label='y')
p.line([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], legend_label="Temp.", line_width=2)
st.bokeh_chart(p)

# PyDeck 3D visualization example
import pydeck as pdk
data = pd.DataFrame({
    'lat': [37.7749, 37.7849, 37.7949],
    'lon': [-122.4194, -122.4094, -122.3994],
    'elevation': [100, 200, 150]
})

st.pydeck_chart(pdk.Deck(
    map_style='mapbox://styles/mapbox/light-v9',
    initial_view_state=pdk.ViewState(
        latitude=37.7749,
        longitude=-122.4194,
        zoom=11,
        pitch=50,
    ),
    layers=[
        pdk.Layer(
            'HexagonLayer',
            data=data,
            get_position='[lon, lat]',
            radius=200,
            elevation_scale=4,
            elevation_range=[0, 1000],
            pickable=True,
            extruded=True,
        ),
    ],
))

# Graphviz example
import graphviz
dot = graphviz.Digraph()
dot.edge('A', 'B')
dot.edge('B', 'C')
dot.edge('A', 'C')
st.graphviz_chart(dot)

Images

Display and manipulate image data from various sources.

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:
    """
    Display an image or list of images.
    
    Parameters:
    - image: Image data (PIL.Image, numpy.ndarray, BytesIO, str path, or URL)
    - caption: Image caption text
    - width: Image width in pixels (None for original size)
    - use_column_width: Whether to use column width ("auto", "always", "never")
    - clamp: Whether to clamp image values to valid range
    - channels: Color channel format ("RGB", "BGR")
    - output_format: Output format ("JPEG", "PNG", "auto")
    """

Usage Example

import streamlit as st
from PIL import Image
import numpy as np

# Display image from file
image = Image.open('path/to/image.jpg')
st.image(image, caption='Sample Image', width=300)

# Display image from URL
st.image('https://example.com/image.jpg', caption='Image from URL')

# Display numpy array as image
img_array = np.random.randint(0, 255, (100, 100, 3), dtype=np.uint8)
st.image(img_array, caption='Generated Image')

# Multiple images in gallery
images = [image1, image2, image3]
captions = ['Image 1', 'Image 2', 'Image 3']
st.image(images, caption=captions, width=200)

# Use column width
st.image(image, use_column_width=True)

Audio and Video

Display audio and video content with built-in media players.

def audio(data, format: str = "audio/wav", start_time: int = 0) -> DeltaGenerator:
    """
    Display an audio player.
    
    Parameters:
    - data: Audio data (bytes, BytesIO, numpy.ndarray, or file path)
    - format: Audio format MIME type
    - start_time: Start time in seconds
    """

def video(data, format: str = "video/mp4", start_time: int = 0) -> DeltaGenerator:
    """
    Display a video player.
    
    Parameters:
    - data: Video data (bytes, BytesIO, numpy.ndarray, or file path)
    - format: Video format MIME type
    - start_time: Start time in seconds
    """

Usage Example

import streamlit as st

# Audio player
audio_file = open('audio.wav', 'rb')
audio_bytes = audio_file.read()
st.audio(audio_bytes, format='audio/wav')

# Video player
video_file = open('video.mp4', 'rb')
video_bytes = video_file.read()
st.video(video_bytes)

# Video with custom start time
st.video('https://example.com/video.mp4', start_time=30)

# Audio from numpy array (synthetic audio)
import numpy as np
sample_rate = 44100
duration = 2  # seconds
t = np.linspace(0, duration, int(sample_rate * duration))
frequency = 440  # A4 note
audio_data = np.sin(2 * np.pi * frequency * t)
st.audio(audio_data, sample_rate=sample_rate)

Chart Configuration and Styling

Most chart functions support additional styling and configuration options:

# Chart with custom dimensions
st.line_chart(data, width=800, height=400)

# Chart using full container width
st.plotly_chart(fig, use_container_width=True)

# Combining charts in layouts
col1, col2 = st.columns(2)
with col1:
    st.line_chart(data1)
with col2:
    st.bar_chart(data2)

Performance Tips

  • Use built-in charts for simple visualizations (faster rendering)
  • Use Plotly for interactive features and complex charts
  • Use use_container_width=True for responsive layouts
  • Consider caching expensive chart generation with @st.cache_data

Install with Tessl CLI

npx tessl i tessl/pypi-streamlit@1.16.0

docs

caching-config.md

charts-media.md

custom-components.md

display-elements.md

index.md

input-widgets.md

layout-containers.md

tile.json