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
@st.cache_data
def load_data(url):
return pd.read_csv(url)
# URL input
url = st.text_input(
"Enter CSV URL",
value="https://raw.githubusercontent.com/mwaskom/seaborn-data/master/penguins.csv"
)
try:
# Load data
df = load_data(url)
# 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),
value=min(10, len(df)))
with col2:
shuffle = st.checkbox("Randomly shuffle data")
# Shuffle if requested
if shuffle:
df = df.sample(frac=1, random_state=42).reset_index(drop=True)
# Display dataframe
st.dataframe(df.head(n_rows))
# Variable selection
st.subheader("Visualization")
columns = df.columns.tolist()
col1, col2 = st.columns(2)
with col1:
var1 = st.selectbox("Select first variable", columns)
with col2:
var2 = st.selectbox("Select second variable",
[None] + [col for col in columns if col != var1])
# Visualization logic
if var2 is None:
# Single variable visualization
if pd.api.types.is_numeric_dtype(df[var1]):
# Numeric: show histogram
fig = px.histogram(df, x=var1, title=f"Distribution of {var1}")
else:
# Categorical: show bar chart
counts = df[var1].value_counts().reset_index()
fig = px.bar(counts, x='index', y=var1, title=f"Counts of {var1}")
else:
# Two variable visualization
if (pd.api.types.is_numeric_dtype(df[var1]) and
pd.api.types.is_numeric_dtype(df[var2])):
# Both numeric: scatter plot
fig = px.scatter(df, x=var1, y=var2,
title=f"{var2} vs {var1}")
elif (pd.api.types.is_numeric_dtype(df[var1]) or
pd.api.types.is_numeric_dtype(df[var2])):
# One numeric, one categorical: box plot
# Make sure categorical is x and numeric is y
if pd.api.types.is_numeric_dtype(df[var1]):
fig = px.box(df, x=var2, y=var1,
title=f"{var1} by {var2}")
else:
fig = px.box(df, x=var1, y=var2,
title=f"{var2} by {var1}")
else:
# Both categorical: heatmap
contingency = pd.crosstab(df[var1], df[var2])
fig = px.imshow(contingency,
title=f"Relationship between {var1} and {var2}")
st.plotly_chart(fig)
except Exception as e:
st.error(f"Error: {str(e)}")
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?