Skip to Content

03. Interactive Charts with Plotly

Advanced40 minutes

1. Static Charts vs Interactive Charts

  • Matplotlib/Seaborn: Fixed charts like images. You can’t zoom in or see detailed values.
  • Plotly: Web-friendly charts. Values appear on mouse hover, and you can zoom in/out.

Streamlit supports st.pyplot() as well, but it’s most powerful when used with st.plotly_chart().


2. Creating Plotly Charts

Let’s create simple charts with the data from Project 1.

❓ Problem 1: Draw Sales Trend Line

Q. Generate hypothetical monthly sales data, draw a Plotly Line Chart, and display it in Streamlit.

import plotly.express as px import pandas as pd import streamlit as st # Generate data df_trend = pd.DataFrame({ 'Date': pd.date_range(start='2024-01-01', periods=6, freq='M'), 'Sales': [10000, 12000, 15000, 13000, 16000, 18000] }) # Create Plotly chart fig = px.line(df_trend, x='Date', y='Sales', title='Monthly Sales Trend', markers=True) # Customize chart (optional) fig.update_layout(title_font_size=20, hovermode='x unified') # Display in Streamlit st.plotly_chart(fig, use_container_width=True)

3. Connecting Filters and Charts (Interaction)

This is the most important part. Charts should change based on the value selected in the sidebar - that’s a real dashboard.

❓ Problem 2: Visualize Filtered Data

Q. Make it so only data corresponding to the ‘Region’ selected in the sidebar is displayed in the chart.

💡

Logic: Get sidebar value -> Filter DataFrame -> Draw chart sequence.

# Prepare data df_sales = pd.DataFrame({ 'Region': ['North', 'North', 'South', 'South', 'East', 'East'], 'Product': ['A', 'B', 'A', 'B', 'A', 'B'], 'Sales': [100, 200, 150, 250, 120, 180] }) # 1. Sidebar filter region_filter = st.sidebar.multiselect( "Select Region", options=df_sales['Region'].unique(), default=df_sales['Region'].unique() ) # 2. Filter data filtered_df = df_sales[df_sales['Region'].isin(region_filter)] # 3. Draw chart (Bar Chart) fig_bar = px.bar( filtered_df, x='Region', y='Sales', color='Product', barmode='group', title=f"Sales by Region: {', '.join(region_filter)}" ) st.plotly_chart(fig_bar, use_container_width=True)

4. Hands-On! Integrating Analysis Results

Now let’s fetch and display the BigQuery data we created earlier. (Requires google-cloud-bigquery authentication on your local machine.)

from google.cloud import bigquery # Use caching (to avoid querying every time) @st.cache_data def load_data(): client = bigquery.Client() query = """ SELECT date, total_sales FROM `your-project-id.retail_analytics_us.daily_sales_summary` ORDER BY date DESC LIMIT 30 """ return client.query(query).to_dataframe() df = load_data() st.line_chart(df.set_index('date'))

💡 Summary

  • Plotly Express (px): The easiest and fastest way to create interactive charts.
  • st.plotly_chart: Draws a Plotly object (fig) on screen. Using use_container_width=True makes it fill the width.
  • Interactivity: Remember the Sidebar Input -> Filter DF -> Update Chart flow.

Congratulations! 🎉 You have now completed an End-to-End Data Analysis Project spanning from data collection (SQL) to analysis (Pandas/ML) and visualization (Streamlit). We hope this Cookbook becomes a great portfolio for your career!

Last updated on

🤖AI 모의면접실전처럼 연습하기