Create an application that has a text field to enter a URL (default value: https://raw.githubusercontent.com/mwaskom/seaborn-data/master/penguins.csv). The app should read the CSV file (and cache it) from the URL and display a DataFrame. Add controls to do the following: - Control how many rows are displayed - A checkbox to determine to randomly shuffle the DataFrame Users select one or two variables and you must determine the best way to visualize them.
To upload files, please first save the app
import streamlit as st
import pandas as pd
import plotly.express as px
import numpy as np
# Cache the data loading function
@st.cache_data
def load_data(url):
try:
# NOTE: Using corsproxy.io because we're in a WASM environment. If running locally,
# you can remove the corsproxy.io prefix. Some websites don't work with the proxy,
# in those cases try removing the proxy prefix.
proxied_url = f"https://corsproxy.io/?{url}"
df = pd.read_csv(proxied_url)
return df, None
except Exception as e:
return None, str(e)
# App title
st.title("Data Visualization Explorer")
# URL input
url = st.text_input(
"Enter CSV URL",
value="https://raw.githubusercontent.com/mwaskom/seaborn-data/master/penguins.csv"
)
df, error = load_data(url)
if error:
st.error(f"Error loading data: {error}")
else:
# Controls
col1, col2 = st.columns(2)
with col1:
n_rows = st.number_input("Number of rows to display",
min_value=1,
max_value=len(df) if df is not None else 1,
value=min(5, len(df) if df is not None else 1))
with col2:
shuffle = st.checkbox("Randomly shuffle data")
# Process DataFrame
if shuffle:
df = df.sample(frac=1, random_state=42).reset_index(drop=True)
# Display DataFrame
st.subheader("Data Preview")
st.dataframe(df.head(n_rows))
# Variable selection for visualization
st.subheader("Visualization")
numeric_cols = df.select_dtypes(include=[np.number]).columns.tolist()
categorical_cols = df.select_dtypes(exclude=[np.number]).columns.tolist()
all_cols = numeric_cols + categorical_cols
col1, col2 = st.columns(2)
with col1:
var1 = st.selectbox("Select first variable", all_cols)
with col2:
remaining_cols = [col for col in all_cols if col != var1]
var2 = st.selectbox("Select second variable (optional)",
["None"] + remaining_cols)
# Create visualization based on selected variables
if var2 == "None":
# Single variable visualization
if var1 in numeric_cols:
fig = px.histogram(df, x=var1, title=f"Distribution of {var1}")
st.plotly_chart(fig)
else:
fig = px.bar(df[var1].value_counts().reset_index(),
x='index', y=var1,
title=f"Count of {var1}")
st.plotly_chart(fig)
else:
# Two variable visualization
if var1 in numeric_cols and var2 in numeric_cols:
# Scatter plot for two numeric variables
fig = px.scatter(df, x=var1, y=var2,
title=f"{var2} vs {var1}")
st.plotly_chart(fig)
elif var1 in numeric_cols and var2 in categorical_cols:
# Box plot for numeric vs categorical
fig = px.box(df, x=var2, y=var1,
title=f"Distribution of {var1} by {var2}")
st.plotly_chart(fig)
elif var1 in categorical_cols and var2 in numeric_cols:
# Box plot for numeric vs categorical
fig = px.box(df, x=var1, y=var2,
title=f"Distribution of {var2} by {var1}")
st.plotly_chart(fig)
else:
# Heatmap for two categorical variables
contingency = pd.crosstab(df[var1], df[var2])
fig = px.imshow(contingency,
title=f"Relationship between {var1} and {var2}")
st.plotly_chart(fig)
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?