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.
Simple, fast charts using Streamlit's native charting engine built on Altair.
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):
"""
Display a line chart.
Parameters:
- data: DataFrame, array-like, or dict with chart data
- x (str): Column name for x-axis values
- y (str or list): Column name(s) for y-axis values
- x_label (str): Custom x-axis label
- y_label (str): Custom y-axis label
- color (str): Column name for color encoding
- width (int): Chart width in pixels
- height (int): Chart height in pixels
- use_container_width (bool): Use full container width
Returns:
None
"""
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):
"""
Display an area chart.
Parameters:
- data: DataFrame, array-like, or dict with chart data
- x (str): Column name for x-axis values
- y (str or list): Column name(s) for y-axis values
- x_label (str): Custom x-axis label
- y_label (str): Custom y-axis label
- color (str): Column name for color encoding
- width (int): Chart width in pixels
- height (int): Chart height in pixels
- use_container_width (bool): Use full container width
- stack (str): Stacking mode ('normalize', 'center', or None)
Returns:
None
"""
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):
"""
Display a bar chart.
Parameters:
- data: DataFrame, array-like, or dict with chart data
- x (str): Column name for x-axis values
- y (str or list): Column name(s) for y-axis values
- x_label (str): Custom x-axis label
- y_label (str): Custom y-axis label
- color (str): Column name for color encoding
- width (int): Chart width in pixels
- height (int): Chart height in pixels
- use_container_width (bool): Use full container width
- horizontal (bool): Create horizontal bar chart
- stack (str): Stacking mode ('normalize', 'center', or None)
Returns:
None
"""
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):
"""
Display a scatter chart.
Parameters:
- data: DataFrame, array-like, or dict with chart data
- x (str): Column name for x-axis values
- y (str): Column name for y-axis values
- x_label (str): Custom x-axis label
- y_label (str): Custom y-axis label
- color (str): Column name for color encoding
- size (str): Column name for size encoding
- width (int): Chart width in pixels
- height (int): Chart height in pixels
- use_container_width (bool): Use full container width
Returns:
None
"""Geographic data visualization with point overlays.
def map(data=None, zoom=None, use_container_width=True, latitude=None, longitude=None, color=None, size=None):
"""
Display a map with points plotted on it.
Parameters:
- data: DataFrame with latitude and longitude columns
- zoom (int): Initial zoom level
- use_container_width (bool): Use full container width
- latitude (str): Column name for latitude values (default: 'latitude', 'lat')
- longitude (str): Column name for longitude values (default: 'longitude', 'lon', 'lng')
- color (str): Column name for color encoding
- size (str): Column name for size encoding
Returns:
None
"""Integration with popular Python visualization libraries.
def plotly_chart(figure_or_data, use_container_width=False, sharing="streamlit", theme="streamlit", **kwargs):
"""
Display an interactive Plotly chart.
Parameters:
- figure_or_data: Plotly figure object or data dict
- use_container_width (bool): Use full container width
- sharing (str): Sharing mode ('streamlit' or 'public')
- theme (str): Theme name ('streamlit' or None)
- **kwargs: Additional Plotly configuration options
Returns:
None
"""
def altair_chart(altair_chart, use_container_width=False, theme="streamlit"):
"""
Display a chart using the Altair library.
Parameters:
- altair_chart: Altair chart object
- use_container_width (bool): Use full container width
- theme (str): Theme name ('streamlit' or None)
Returns:
None
"""
def vega_lite_chart(data=None, spec=None, use_container_width=False, theme="streamlit", **kwargs):
"""
Display a chart using the Vega-Lite library.
Parameters:
- data: Chart data (DataFrame, dict, or None if data is in spec)
- spec (dict): Vega-Lite specification
- use_container_width (bool): Use full container width
- theme (str): Theme name ('streamlit' or None)
- **kwargs: Additional chart data or specification options
Returns:
None
"""
def pyplot(fig=None, clear_figure=None, use_container_width=True, **kwargs):
"""
Display a matplotlib.pyplot figure.
Parameters:
- fig: Matplotlib figure object (uses current figure if None)
- clear_figure (bool): Clear the figure after displaying
- use_container_width (bool): Use full container width
- **kwargs: Additional matplotlib configuration options
Returns:
None
"""
def bokeh_chart(figure, use_container_width=False):
"""
Display an interactive Bokeh chart.
Parameters:
- figure: Bokeh figure object
- use_container_width (bool): Use full container width
Returns:
None
"""
def pydeck_chart(pydeck_obj=None, use_container_width=False):
"""
Display a chart using the PyDeck library for 3D visualizations.
Parameters:
- pydeck_obj: PyDeck Deck object
- use_container_width (bool): Use full container width
Returns:
None
"""
def graphviz_chart(figure_or_dot, use_container_width=False):
"""
Display a graph using the Graphviz library.
Parameters:
- figure_or_dot: Graphviz figure object or DOT string
- use_container_width (bool): Use full container width
Returns:
None
"""import streamlit as st
import pandas as pd
import numpy as np
# Generate sample data
chart_data = pd.DataFrame({
'date': pd.date_range('2023-01-01', periods=30),
'sales': np.random.randint(100, 1000, 30),
'profit': np.random.randint(10, 100, 30),
'region': np.random.choice(['North', 'South', 'East', 'West'], 30)
})
# Line chart
st.subheader("Sales Trend")
st.line_chart(
chart_data,
x='date',
y='sales',
use_container_width=True
)
# Multiple series line chart
st.subheader("Sales vs Profit")
st.line_chart(
chart_data,
x='date',
y=['sales', 'profit'],
x_label="Date",
y_label="Amount ($)"
)
# Bar chart with color encoding
st.subheader("Sales by Region")
region_data = chart_data.groupby('region')['sales'].sum().reset_index()
st.bar_chart(
region_data,
x='region',
y='sales',
color='region'
)
# Scatter plot
st.subheader("Sales vs Profit Correlation")
st.scatter_chart(
chart_data,
x='sales',
y='profit',
color='region',
size='sales'
)# Sample location data
map_data = pd.DataFrame({
'latitude': [37.7749, 40.7128, 41.8781, 34.0522],
'longitude': [-122.4194, -74.0060, -87.6298, -118.2437],
'city': ['San Francisco', 'New York', 'Chicago', 'Los Angeles'],
'population': [883305, 8175133, 2695598, 3971883]
})
st.subheader("City Locations")
st.map(
map_data,
latitude='latitude',
longitude='longitude',
size='population',
zoom=3
)import matplotlib.pyplot as plt
# Create matplotlib figure
fig, ax = plt.subplots(figsize=(10, 6))
ax.hist(np.random.randn(1000), bins=30, alpha=0.7)
ax.set_title('Distribution of Random Values')
ax.set_xlabel('Value')
ax.set_ylabel('Frequency')
st.subheader("Matplotlib Histogram")
st.pyplot(fig)import plotly.express as px
import plotly.graph_objects as go
# Simple Plotly chart
fig = px.scatter(
chart_data,
x='sales',
y='profit',
color='region',
size='sales',
title='Sales vs Profit by Region'
)
st.subheader("Interactive Plotly Scatter")
st.plotly_chart(fig, use_container_width=True)
# Advanced Plotly chart with multiple traces
fig = go.Figure()
fig.add_trace(go.Scatter(
x=chart_data['date'],
y=chart_data['sales'],
mode='lines+markers',
name='Sales',
line=dict(color='blue')
))
fig.add_trace(go.Scatter(
x=chart_data['date'],
y=chart_data['profit'],
mode='lines+markers',
name='Profit',
line=dict(color='red')
))
fig.update_layout(title='Sales and Profit Over Time')
st.subheader("Multi-trace Plotly Chart")
st.plotly_chart(fig, use_container_width=True)import altair as alt
# Create Altair chart
chart = alt.Chart(chart_data).mark_circle(size=100).encode(
x='sales:Q',
y='profit:Q',
color='region:N',
tooltip=['date:T', 'sales:Q', 'profit:Q', 'region:N']
).interactive()
st.subheader("Interactive Altair Chart")
st.altair_chart(chart, use_container_width=True)import pydeck as pdk
# 3D visualization with PyDeck
layer = pdk.Layer(
'ScatterplotLayer',
data=map_data,
get_position=['longitude', 'latitude'],
get_radius='population',
radius_scale=0.0001,
get_color=[255, 140, 0],
elevation_scale=4,
elevation_range=[0, 1000],
pickable=True,
extruded=True,
)
view_state = pdk.ViewState(
latitude=39.8283,
longitude=-98.5795,
zoom=3,
pitch=50,
)
deck = pdk.Deck(
layers=[layer],
initial_view_state=view_state,
tooltip={'text': '{city}\nPopulation: {population}'}
)
st.subheader("3D City Population Visualization")
st.pydeck_chart(deck)# Custom Vega-Lite specification
spec = {
"mark": "bar",
"encoding": {
"x": {"field": "region", "type": "nominal"},
"y": {"field": "sales", "type": "quantitative", "aggregate": "mean"},
"color": {"field": "region", "type": "nominal"}
}
}
st.subheader("Custom Vega-Lite Chart")
st.vega_lite_chart(chart_data, spec, use_container_width=True)# Plotly chart with custom theme disabled
fig = px.bar(
region_data,
x='region',
y='sales',
title='Sales by Region (Default Plotly Theme)'
)
st.plotly_chart(fig, theme=None) # Use Plotly's default theme
# Altair chart with Streamlit theme
chart = alt.Chart(chart_data).mark_bar().encode(
x='region:N',
y='mean(sales):Q',
color='region:N'
)
st.altair_chart(chart, theme="streamlit") # Use Streamlit theme