- Spec files
pypi-streamlit
Describes: pkg:pypi/streamlit@1.49.x
- Description
- A faster way to build and share data apps
- Author
- tessl
- Last updated
charts-visualizations.md docs/
1# Charts and Visualizations23Comprehensive charting capabilities including built-in charts and third-party library integrations. Streamlit provides both simple chart functions and full integration with popular visualization libraries.45## Capabilities67### Built-in Charts89Simple, fast charts using Streamlit's native charting engine built on Altair.1011```python { .api }12def line_chart(data=None, x=None, y=None, x_label=None, y_label=None, color=None, width=None, height=None, use_container_width=True):13"""14Display a line chart.1516Parameters:17- data: DataFrame, array-like, or dict with chart data18- x (str): Column name for x-axis values19- y (str or list): Column name(s) for y-axis values20- x_label (str): Custom x-axis label21- y_label (str): Custom y-axis label22- color (str): Column name for color encoding23- width (int): Chart width in pixels24- height (int): Chart height in pixels25- use_container_width (bool): Use full container width2627Returns:28None29"""3031def 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):32"""33Display an area chart.3435Parameters:36- data: DataFrame, array-like, or dict with chart data37- x (str): Column name for x-axis values38- y (str or list): Column name(s) for y-axis values39- x_label (str): Custom x-axis label40- y_label (str): Custom y-axis label41- color (str): Column name for color encoding42- width (int): Chart width in pixels43- height (int): Chart height in pixels44- use_container_width (bool): Use full container width45- stack (str): Stacking mode ('normalize', 'center', or None)4647Returns:48None49"""5051def 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):52"""53Display a bar chart.5455Parameters:56- data: DataFrame, array-like, or dict with chart data57- x (str): Column name for x-axis values58- y (str or list): Column name(s) for y-axis values59- x_label (str): Custom x-axis label60- y_label (str): Custom y-axis label61- color (str): Column name for color encoding62- width (int): Chart width in pixels63- height (int): Chart height in pixels64- use_container_width (bool): Use full container width65- horizontal (bool): Create horizontal bar chart66- stack (str): Stacking mode ('normalize', 'center', or None)6768Returns:69None70"""7172def 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):73"""74Display a scatter chart.7576Parameters:77- data: DataFrame, array-like, or dict with chart data78- x (str): Column name for x-axis values79- y (str): Column name for y-axis values80- x_label (str): Custom x-axis label81- y_label (str): Custom y-axis label82- color (str): Column name for color encoding83- size (str): Column name for size encoding84- width (int): Chart width in pixels85- height (int): Chart height in pixels86- use_container_width (bool): Use full container width8788Returns:89None90"""91```9293### Map Visualizations9495Geographic data visualization with point overlays.9697```python { .api }98def map(data=None, zoom=None, use_container_width=True, latitude=None, longitude=None, color=None, size=None):99"""100Display a map with points plotted on it.101102Parameters:103- data: DataFrame with latitude and longitude columns104- zoom (int): Initial zoom level105- use_container_width (bool): Use full container width106- latitude (str): Column name for latitude values (default: 'latitude', 'lat')107- longitude (str): Column name for longitude values (default: 'longitude', 'lon', 'lng')108- color (str): Column name for color encoding109- size (str): Column name for size encoding110111Returns:112None113"""114```115116### Third-Party Chart Libraries117118Integration with popular Python visualization libraries.119120```python { .api }121def plotly_chart(figure_or_data, use_container_width=False, sharing="streamlit", theme="streamlit", **kwargs):122"""123Display an interactive Plotly chart.124125Parameters:126- figure_or_data: Plotly figure object or data dict127- use_container_width (bool): Use full container width128- sharing (str): Sharing mode ('streamlit' or 'public')129- theme (str): Theme name ('streamlit' or None)130- **kwargs: Additional Plotly configuration options131132Returns:133None134"""135136def altair_chart(altair_chart, use_container_width=False, theme="streamlit"):137"""138Display a chart using the Altair library.139140Parameters:141- altair_chart: Altair chart object142- use_container_width (bool): Use full container width143- theme (str): Theme name ('streamlit' or None)144145Returns:146None147"""148149def vega_lite_chart(data=None, spec=None, use_container_width=False, theme="streamlit", **kwargs):150"""151Display a chart using the Vega-Lite library.152153Parameters:154- data: Chart data (DataFrame, dict, or None if data is in spec)155- spec (dict): Vega-Lite specification156- use_container_width (bool): Use full container width157- theme (str): Theme name ('streamlit' or None)158- **kwargs: Additional chart data or specification options159160Returns:161None162"""163164def pyplot(fig=None, clear_figure=None, use_container_width=True, **kwargs):165"""166Display a matplotlib.pyplot figure.167168Parameters:169- fig: Matplotlib figure object (uses current figure if None)170- clear_figure (bool): Clear the figure after displaying171- use_container_width (bool): Use full container width172- **kwargs: Additional matplotlib configuration options173174Returns:175None176"""177178def bokeh_chart(figure, use_container_width=False):179"""180Display an interactive Bokeh chart.181182Parameters:183- figure: Bokeh figure object184- use_container_width (bool): Use full container width185186Returns:187None188"""189190def pydeck_chart(pydeck_obj=None, use_container_width=False):191"""192Display a chart using the PyDeck library for 3D visualizations.193194Parameters:195- pydeck_obj: PyDeck Deck object196- use_container_width (bool): Use full container width197198Returns:199None200"""201202def graphviz_chart(figure_or_dot, use_container_width=False):203"""204Display a graph using the Graphviz library.205206Parameters:207- figure_or_dot: Graphviz figure object or DOT string208- use_container_width (bool): Use full container width209210Returns:211None212"""213```214215## Usage Examples216217### Built-in Charts218219```python220import streamlit as st221import pandas as pd222import numpy as np223224# Generate sample data225chart_data = pd.DataFrame({226'date': pd.date_range('2023-01-01', periods=30),227'sales': np.random.randint(100, 1000, 30),228'profit': np.random.randint(10, 100, 30),229'region': np.random.choice(['North', 'South', 'East', 'West'], 30)230})231232# Line chart233st.subheader("Sales Trend")234st.line_chart(235chart_data,236x='date',237y='sales',238use_container_width=True239)240241# Multiple series line chart242st.subheader("Sales vs Profit")243st.line_chart(244chart_data,245x='date',246y=['sales', 'profit'],247x_label="Date",248y_label="Amount ($)"249)250251# Bar chart with color encoding252st.subheader("Sales by Region")253region_data = chart_data.groupby('region')['sales'].sum().reset_index()254st.bar_chart(255region_data,256x='region',257y='sales',258color='region'259)260261# Scatter plot262st.subheader("Sales vs Profit Correlation")263st.scatter_chart(264chart_data,265x='sales',266y='profit',267color='region',268size='sales'269)270```271272### Map Visualization273274```python275# Sample location data276map_data = pd.DataFrame({277'latitude': [37.7749, 40.7128, 41.8781, 34.0522],278'longitude': [-122.4194, -74.0060, -87.6298, -118.2437],279'city': ['San Francisco', 'New York', 'Chicago', 'Los Angeles'],280'population': [883305, 8175133, 2695598, 3971883]281})282283st.subheader("City Locations")284st.map(285map_data,286latitude='latitude',287longitude='longitude',288size='population',289zoom=3290)291```292293### Matplotlib Integration294295```python296import matplotlib.pyplot as plt297298# Create matplotlib figure299fig, ax = plt.subplots(figsize=(10, 6))300ax.hist(np.random.randn(1000), bins=30, alpha=0.7)301ax.set_title('Distribution of Random Values')302ax.set_xlabel('Value')303ax.set_ylabel('Frequency')304305st.subheader("Matplotlib Histogram")306st.pyplot(fig)307```308309### Plotly Integration310311```python312import plotly.express as px313import plotly.graph_objects as go314315# Simple Plotly chart316fig = px.scatter(317chart_data,318x='sales',319y='profit',320color='region',321size='sales',322title='Sales vs Profit by Region'323)324325st.subheader("Interactive Plotly Scatter")326st.plotly_chart(fig, use_container_width=True)327328# Advanced Plotly chart with multiple traces329fig = go.Figure()330fig.add_trace(go.Scatter(331x=chart_data['date'],332y=chart_data['sales'],333mode='lines+markers',334name='Sales',335line=dict(color='blue')336))337fig.add_trace(go.Scatter(338x=chart_data['date'],339y=chart_data['profit'],340mode='lines+markers',341name='Profit',342line=dict(color='red')343))344fig.update_layout(title='Sales and Profit Over Time')345346st.subheader("Multi-trace Plotly Chart")347st.plotly_chart(fig, use_container_width=True)348```349350### Altair Integration351352```python353import altair as alt354355# Create Altair chart356chart = alt.Chart(chart_data).mark_circle(size=100).encode(357x='sales:Q',358y='profit:Q',359color='region:N',360tooltip=['date:T', 'sales:Q', 'profit:Q', 'region:N']361).interactive()362363st.subheader("Interactive Altair Chart")364st.altair_chart(chart, use_container_width=True)365```366367### Advanced Visualization with PyDeck368369```python370import pydeck as pdk371372# 3D visualization with PyDeck373layer = pdk.Layer(374'ScatterplotLayer',375data=map_data,376get_position=['longitude', 'latitude'],377get_radius='population',378radius_scale=0.0001,379get_color=[255, 140, 0],380elevation_scale=4,381elevation_range=[0, 1000],382pickable=True,383extruded=True,384)385386view_state = pdk.ViewState(387latitude=39.8283,388longitude=-98.5795,389zoom=3,390pitch=50,391)392393deck = pdk.Deck(394layers=[layer],395initial_view_state=view_state,396tooltip={'text': '{city}\nPopulation: {population}'}397)398399st.subheader("3D City Population Visualization")400st.pydeck_chart(deck)401```402403### Vega-Lite Specification404405```python406# Custom Vega-Lite specification407spec = {408"mark": "bar",409"encoding": {410"x": {"field": "region", "type": "nominal"},411"y": {"field": "sales", "type": "quantitative", "aggregate": "mean"},412"color": {"field": "region", "type": "nominal"}413}414}415416st.subheader("Custom Vega-Lite Chart")417st.vega_lite_chart(chart_data, spec, use_container_width=True)418```419420### Chart Theming and Customization421422```python423# Plotly chart with custom theme disabled424fig = px.bar(425region_data,426x='region',427y='sales',428title='Sales by Region (Default Plotly Theme)'429)430431st.plotly_chart(fig, theme=None) # Use Plotly's default theme432433# Altair chart with Streamlit theme434chart = alt.Chart(chart_data).mark_bar().encode(435x='region:N',436y='mean(sales):Q',437color='region:N'438)439440st.altair_chart(chart, theme="streamlit") # Use Streamlit theme441```