Create a Streamlit 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 The app should also allow plotting the entire CSV. 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 seaborn as sns
import matplotlib.pyplot as plt
# Title of the app
st.title('Penguins Data Visualization')
# Entry field for URL with a default value
url = st.text_input('Enter the URL to the CSV file:',
'https://raw.githubusercontent.com/mwaskom/seaborn-data/master/penguins.csv')
# Load and cache the DataFrame
@st.cache_data
def load_data(url):
return pd.read_csv(url)
# Read the data
try:
df = load_data(url)
st.write('Data successfully loaded!')
except Exception as e:
st.write('Error loading data:', e)
df = pd.DataFrame()
# Controls to display number of rows and shuffle the DataFrame
if not df.empty:
num_rows = st.slider('Select number of rows to display:', 1, len(df), 10)
shuffle = st.checkbox('Shuffle DataFrame?')
if shuffle:
df = df.sample(frac=1).reset_index(drop=True)
st.dataframe(df.head(num_rows))
# Visualization options
st.subheader('Visualize Data')
variables = df.columns.tolist()
x_axis = st.selectbox('Select X-axis variable:', variables)
y_axis = st.selectbox('Select Y-axis variable (leave blank for univariate):', variables + [None])
if st.button('Plot'):
if y_axis:
# Scatter plot for two variables
sns.scatterplot(data=df, x=x_axis, y=y_axis)
plt.title(f'Scatter Plot of {y_axis} vs {x_axis}')
else:
# Histogram for single variable
sns.histplot(df[x_axis], bins=20)
plt.title(f'Histogram of {x_axis}')
st.pyplot()
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?