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 numpy as np
import altair as alt
@st.cache_data
def load_data(url):
return pd.read_csv(url)
st.title('Penguins Data Viewer')
# URL input field
url = st.text_input('Enter a URL for a CSV file:',
'https://raw.githubusercontent.com/mwaskom/seaborn-data/master/penguins.csv')
# Load data
try:
df = load_data(url)
st.success('Data loaded successfully')
except Exception as e:
st.error(f'Error loading data: {e}')
# Display options
num_rows = st.number_input('Select number of rows to display:', min_value=1, max_value=len(df), value=5)
shuffle = st.checkbox('Shuffle DataFrame')
if shuffle:
df = df.sample(frac=1).reset_index(drop=True) # Shuffle dataframe
# Display the DataFrame
st.write(df.head(num_rows))
# Variable selection for visualization
columns = df.select_dtypes(include=['float64', 'int64']).columns.tolist()
selected_vars = st.multiselect('Select one or two variables to visualize:', columns)
# Visualization
if len(selected_vars) == 1:
st.write(f'**Histogram of {selected_vars[0]}**')
chart = alt.Chart(df).mark_bar().encode(
alt.X(selected_vars[0], bin=True),
y='count()'
)
st.altair_chart(chart, use_container_width=True)
elif len(selected_vars) == 2:
st.write(f'**Scatter plot of {selected_vars[0]} vs {selected_vars[1]}**')
chart = alt.Chart(df).mark_circle().encode(
alt.X(selected_vars[0]),
alt.Y(selected_vars[1]),
tooltip=list(selected_vars)
).interactive()
st.altair_chart(chart, use_container_width=True)
else:
st.warning('Please select one or two variables for visualization.')
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?