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 matplotlib.pyplot as plt
import random
# Streamlit app
st.title('CSV Data Viewer')
# URL text input
url = st.text_input('Enter CSV URL:',
'https://raw.githubusercontent.com/mwaskom/seaborn-data/master/penguins.csv')
# Load data with caching
@st.cache_data
def load_data(url):
return pd.read_csv(url)
# Load the CSV data
try:
df = load_data(url)
st.write('Data loaded successfully!')
except Exception as e:
st.error(f'Error loading data: {e}')
# Control: number of rows displayed
num_rows = st.slider('Select number of rows to display:', 1, len(df), 5)
if num_rows:
st.dataframe(df.head(num_rows))
# Checkbox for shuffling the DataFrame
shuffle = st.checkbox('Shuffle DataFrame')
if shuffle:
df = df.sample(frac=1).reset_index(drop=True)
# Plotting options
st.sidebar.header('Plotting Options')
variables = df.columns.tolist()
var_x = st.sidebar.selectbox('Select variable for X-axis:', variables)
var_y = st.sidebar.selectbox('Select variable for Y-axis (optional):', [''] + variables)
# Plotting
if st.sidebar.button('Plot'):
plt.figure(figsize=(10, 5))
if var_y:
plt.scatter(df[var_x], df[var_y], alpha=0.5)
plt.xlabel(var_x)
plt.ylabel(var_y)
plt.title(f'Scatter Plot of {var_y} vs {var_x}')
else:
df[var_x].value_counts().plot(kind='bar')
plt.xlabel(var_x)
plt.title(f'Bar Plot of {var_x}')
st.pyplot(plt)
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?