Update src/streamlit_app.py
Browse files- src/streamlit_app.py +397 -38
src/streamlit_app.py
CHANGED
|
@@ -1,40 +1,399 @@
|
|
| 1 |
-
import altair as alt
|
| 2 |
-
import numpy as np
|
| 3 |
-
import pandas as pd
|
| 4 |
import streamlit as st
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
|
| 10 |
-
If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
|
| 11 |
-
forums](https://discuss.streamlit.io).
|
| 12 |
-
|
| 13 |
-
In the meantime, below is an example of what you can do with just a few lines of code:
|
| 14 |
-
"""
|
| 15 |
-
|
| 16 |
-
num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
|
| 17 |
-
num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
|
| 18 |
-
|
| 19 |
-
indices = np.linspace(0, 1, num_points)
|
| 20 |
-
theta = 2 * np.pi * num_turns * indices
|
| 21 |
-
radius = indices
|
| 22 |
-
|
| 23 |
-
x = radius * np.cos(theta)
|
| 24 |
-
y = radius * np.sin(theta)
|
| 25 |
-
|
| 26 |
-
df = pd.DataFrame({
|
| 27 |
-
"x": x,
|
| 28 |
-
"y": y,
|
| 29 |
-
"idx": indices,
|
| 30 |
-
"rand": np.random.randn(num_points),
|
| 31 |
-
})
|
| 32 |
-
|
| 33 |
-
st.altair_chart(alt.Chart(df, height=700, width=700)
|
| 34 |
-
.mark_point(filled=True)
|
| 35 |
-
.encode(
|
| 36 |
-
x=alt.X("x", axis=None),
|
| 37 |
-
y=alt.Y("y", axis=None),
|
| 38 |
-
color=alt.Color("idx", legend=None, scale=alt.Scale()),
|
| 39 |
-
size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
|
| 40 |
-
))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import numpy as np
|
| 4 |
+
import plotly.express as px
|
| 5 |
+
import plotly.graph_objects as go
|
| 6 |
+
import plotly.io as pio
|
| 7 |
+
from plotly.subplots import make_subplots
|
| 8 |
+
import io
|
| 9 |
+
|
| 10 |
+
# Metadata
|
| 11 |
+
AUTHOR = "Eduardo Nacimiento García"
|
| 12 |
+
EMAIL = "[email protected]"
|
| 13 |
+
LICENSE = "Apache 2.0"
|
| 14 |
+
|
| 15 |
+
# Page config
|
| 16 |
+
st.set_page_config(
|
| 17 |
+
page_title="SimpleViz",
|
| 18 |
+
page_icon="🎨",
|
| 19 |
+
layout="wide",
|
| 20 |
+
initial_sidebar_state="expanded",
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
# Title
|
| 24 |
+
st.title("🎨 SimpleViz")
|
| 25 |
+
st.markdown(f"**Author:** {AUTHOR} | **Email:** {EMAIL} | **License:** {LICENSE}")
|
| 26 |
+
st.write("""
|
| 27 |
+
Upload a CSV or use the demo dataset to create beautiful, interactive visualizations in seconds.
|
| 28 |
+
""")
|
| 29 |
+
|
| 30 |
+
# === GENERATE DEMO DATASET ===
|
| 31 |
+
@st.cache_data
|
| 32 |
+
def create_demo_data():
|
| 33 |
+
np.random.seed(42)
|
| 34 |
+
n = 500
|
| 35 |
+
data = {
|
| 36 |
+
"Age": np.random.normal(35, 12, n).astype(int),
|
| 37 |
+
"Income": np.random.normal(45000, 15000, n),
|
| 38 |
+
"Satisfaction": np.random.randint(1, 11, n),
|
| 39 |
+
"City": np.random.choice(["Madrid", "Barcelona", "Valencia", "Seville"], n),
|
| 40 |
+
"Gender": np.random.choice(["M", "F"], n, p=[0.6, 0.4]),
|
| 41 |
+
"Purchase": np.random.choice([0, 1], n, p=[0.7, 0.3]),
|
| 42 |
+
"Date": pd.date_range(start="2023-01-01", periods=n, freq="D")
|
| 43 |
+
}
|
| 44 |
+
df = pd.DataFrame(data)
|
| 45 |
+
# Introduce some nulls for realism
|
| 46 |
+
df.loc[np.random.choice(df.index, 15), "Income"] = np.nan
|
| 47 |
+
return df
|
| 48 |
+
|
| 49 |
+
# === LOAD DATA ===
|
| 50 |
+
if st.button("🧪 Load Demo Dataset"):
|
| 51 |
+
st.session_state['df'] = create_demo_data()
|
| 52 |
+
st.success("✅ Demo dataset loaded!")
|
| 53 |
+
|
| 54 |
+
uploaded_file = st.file_uploader("📂 Upload your CSV file", type=["csv"])
|
| 55 |
+
|
| 56 |
+
if uploaded_file:
|
| 57 |
+
df = pd.read_csv(uploaded_file)
|
| 58 |
+
st.session_state['df'] = df
|
| 59 |
+
st.success("✅ File uploaded successfully.")
|
| 60 |
+
|
| 61 |
+
if 'df' not in st.session_state:
|
| 62 |
+
st.info("👆 Upload a CSV or click 'Load Demo Dataset' to begin.")
|
| 63 |
+
st.stop()
|
| 64 |
+
|
| 65 |
+
df = st.session_state['df']
|
| 66 |
+
|
| 67 |
+
# Show data preview
|
| 68 |
+
with st.expander("🔍 Data Preview (first 10 rows)"):
|
| 69 |
+
st.dataframe(df.head(10))
|
| 70 |
+
|
| 71 |
+
# Basic info
|
| 72 |
+
st.subheader("📌 Dataset Info")
|
| 73 |
+
col1, col2, col3 = st.columns(3)
|
| 74 |
+
col1.metric("Rows", df.shape[0])
|
| 75 |
+
col2.metric("Columns", df.shape[1])
|
| 76 |
+
col3.metric("Missing Values", df.isnull().sum().sum())
|
| 77 |
+
|
| 78 |
+
# === AUTO-VISUALIZATION RECOMMENDATIONS ===
|
| 79 |
+
st.header("✨ Smart Visualization Suggestions")
|
| 80 |
+
|
| 81 |
+
numeric_cols = df.select_dtypes(include=[np.number]).columns.tolist()
|
| 82 |
+
categorical_cols = df.select_dtypes(include=['object', 'category']).columns.tolist()
|
| 83 |
+
datetime_cols = df.select_dtypes(include=['datetime', 'datetime64']).columns.tolist()
|
| 84 |
+
|
| 85 |
+
if datetime_cols:
|
| 86 |
+
date_col = datetime_cols[0]
|
| 87 |
+
else:
|
| 88 |
+
date_col = None
|
| 89 |
+
|
| 90 |
+
# Suggest visualizations based on data types
|
| 91 |
+
suggestions = []
|
| 92 |
+
|
| 93 |
+
if len(numeric_cols) >= 2:
|
| 94 |
+
suggestions.append({
|
| 95 |
+
"name": "Scatter Plot",
|
| 96 |
+
"description": "Visualize relationship between two numeric variables",
|
| 97 |
+
"plot_type": "scatter",
|
| 98 |
+
"x": numeric_cols[0],
|
| 99 |
+
"y": numeric_cols[1] if len(numeric_cols) > 1 else numeric_cols[0]
|
| 100 |
+
})
|
| 101 |
+
|
| 102 |
+
if len(numeric_cols) >= 1:
|
| 103 |
+
suggestions.append({
|
| 104 |
+
"name": "Histogram",
|
| 105 |
+
"description": "Distribution of a numeric variable",
|
| 106 |
+
"plot_type": "histogram",
|
| 107 |
+
"x": numeric_cols[0]
|
| 108 |
+
})
|
| 109 |
+
|
| 110 |
+
if len(categorical_cols) >= 1 and len(numeric_cols) >= 1:
|
| 111 |
+
suggestions.append({
|
| 112 |
+
"name": "Bar Plot (Mean)",
|
| 113 |
+
"description": "Compare mean of numeric variable across categories",
|
| 114 |
+
"plot_type": "bar",
|
| 115 |
+
"x": categorical_cols[0],
|
| 116 |
+
"y": numeric_cols[0]
|
| 117 |
+
})
|
| 118 |
+
|
| 119 |
+
if len(categorical_cols) >= 2:
|
| 120 |
+
suggestions.append({
|
| 121 |
+
"name": "Stacked Bar Plot",
|
| 122 |
+
"description": "Relationship between two categorical variables",
|
| 123 |
+
"plot_type": "stacked_bar",
|
| 124 |
+
"x": categorical_cols[0],
|
| 125 |
+
"color": categorical_cols[1] if len(categorical_cols) > 1 else categorical_cols[0]
|
| 126 |
+
})
|
| 127 |
+
|
| 128 |
+
if date_col and len(numeric_cols) >= 1:
|
| 129 |
+
suggestions.append({
|
| 130 |
+
"name": "Time Series Line Plot",
|
| 131 |
+
"description": "Trend of numeric variable over time",
|
| 132 |
+
"plot_type": "line",
|
| 133 |
+
"x": date_col,
|
| 134 |
+
"y": numeric_cols[0]
|
| 135 |
+
})
|
| 136 |
+
|
| 137 |
+
if len(numeric_cols) >= 3:
|
| 138 |
+
suggestions.append({
|
| 139 |
+
"name": "Scatter Plot with Color",
|
| 140 |
+
"description": "Scatter plot with third variable as color",
|
| 141 |
+
"plot_type": "scatter_color",
|
| 142 |
+
"x": numeric_cols[0],
|
| 143 |
+
"y": numeric_cols[1],
|
| 144 |
+
"color": numeric_cols[2]
|
| 145 |
+
})
|
| 146 |
+
|
| 147 |
+
if len(numeric_cols) >= 2:
|
| 148 |
+
suggestions.append({
|
| 149 |
+
"name": "Box Plot",
|
| 150 |
+
"description": "Distribution and outliers of numeric variable by category",
|
| 151 |
+
"plot_type": "box",
|
| 152 |
+
"x": categorical_cols[0] if categorical_cols else None,
|
| 153 |
+
"y": numeric_cols[0]
|
| 154 |
+
})
|
| 155 |
+
|
| 156 |
+
if len(numeric_cols) >= 2:
|
| 157 |
+
suggestions.append({
|
| 158 |
+
"name": "Correlation Heatmap",
|
| 159 |
+
"description": "Correlation matrix of numeric variables",
|
| 160 |
+
"plot_type": "heatmap",
|
| 161 |
+
"cols": numeric_cols[:5] # Limit to 5 columns for readability
|
| 162 |
+
})
|
| 163 |
+
|
| 164 |
+
# Display suggestions
|
| 165 |
+
for i, suggestion in enumerate(suggestions):
|
| 166 |
+
with st.expander(f"🎨 Suggestion {i+1}: {suggestion['name']}"):
|
| 167 |
+
st.write(suggestion["description"])
|
| 168 |
+
if st.button(f"Create {suggestion['name']}", key=f"sug_{i}"):
|
| 169 |
+
st.session_state['selected_suggestion'] = suggestion
|
| 170 |
+
|
| 171 |
+
# === CUSTOM VISUALIZATION BUILDER ===
|
| 172 |
+
st.header("🛠️ Custom Visualization Builder")
|
| 173 |
+
|
| 174 |
+
plot_types = [
|
| 175 |
+
"Scatter Plot",
|
| 176 |
+
"Line Plot",
|
| 177 |
+
"Bar Plot",
|
| 178 |
+
"Histogram",
|
| 179 |
+
"Box Plot",
|
| 180 |
+
"Violin Plot",
|
| 181 |
+
"Pie Chart",
|
| 182 |
+
"Heatmap (Correlation)"
|
| 183 |
+
]
|
| 184 |
+
|
| 185 |
+
selected_plot = st.selectbox("Choose plot type:", plot_types)
|
| 186 |
+
|
| 187 |
+
fig = None
|
| 188 |
+
|
| 189 |
+
if selected_plot == "Scatter Plot":
|
| 190 |
+
col1, col2 = st.columns(2)
|
| 191 |
+
with col1:
|
| 192 |
+
x_col = st.selectbox("X-axis:", numeric_cols)
|
| 193 |
+
with col2:
|
| 194 |
+
y_col = st.selectbox("Y-axis:", [col for col in numeric_cols if col != x_col] if len(numeric_cols) > 1 else numeric_cols)
|
| 195 |
+
|
| 196 |
+
color_col = st.selectbox("Color by (optional):", [None] + categorical_cols + numeric_cols, key="scatter_color")
|
| 197 |
+
size_col = st.selectbox("Size by (optional):", [None] + numeric_cols, key="scatter_size")
|
| 198 |
+
|
| 199 |
+
title = st.text_input("Plot title:", f"{y_col} vs {x_col}")
|
| 200 |
+
|
| 201 |
+
if st.button("Generate Scatter Plot"):
|
| 202 |
+
fig = px.scatter(df, x=x_col, y=y_col, color=color_col, size=size_col, title=title)
|
| 203 |
+
|
| 204 |
+
elif selected_plot == "Line Plot":
|
| 205 |
+
if not datetime_cols and not categorical_cols:
|
| 206 |
+
st.warning("No suitable columns for line plot. Need datetime or categorical x-axis.")
|
| 207 |
+
else:
|
| 208 |
+
available_x = datetime_cols + categorical_cols if datetime_cols else categorical_cols
|
| 209 |
+
col1, col2 = st.columns(2)
|
| 210 |
+
with col1:
|
| 211 |
+
x_col = st.selectbox("X-axis:", available_x)
|
| 212 |
+
with col2:
|
| 213 |
+
y_col = st.selectbox("Y-axis:", numeric_cols)
|
| 214 |
+
|
| 215 |
+
color_col = st.selectbox("Color by (optional):", [None] + categorical_cols, key="line_color")
|
| 216 |
+
title = st.text_input("Plot title:", f"{y_col} over {x_col}")
|
| 217 |
+
|
| 218 |
+
if st.button("Generate Line Plot"):
|
| 219 |
+
fig = px.line(df, x=x_col, y=y_col, color=color_col, title=title, markers=True)
|
| 220 |
+
|
| 221 |
+
elif selected_plot == "Bar Plot":
|
| 222 |
+
if not categorical_cols:
|
| 223 |
+
st.warning("No categorical columns available for bar plot.")
|
| 224 |
+
else:
|
| 225 |
+
col1, col2 = st.columns(2)
|
| 226 |
+
with col1:
|
| 227 |
+
x_col = st.selectbox("Category column:", categorical_cols)
|
| 228 |
+
with col2:
|
| 229 |
+
y_col = st.selectbox("Value column:", numeric_cols)
|
| 230 |
+
|
| 231 |
+
agg_func = st.selectbox("Aggregation:", ["Mean", "Sum", "Count", "Median"])
|
| 232 |
+
color_col = st.selectbox("Color by (optional):", [None] + categorical_cols, key="bar_color")
|
| 233 |
+
title = st.text_input("Plot title:", f"{agg_func} of {y_col} by {x_col}")
|
| 234 |
+
|
| 235 |
+
if st.button("Generate Bar Plot"):
|
| 236 |
+
if agg_func == "Mean":
|
| 237 |
+
fig = px.bar(df, x=x_col, y=y_col, color=color_col, title=title)
|
| 238 |
+
elif agg_func == "Sum":
|
| 239 |
+
fig_data = df.groupby(x_col)[y_col].sum().reset_index()
|
| 240 |
+
fig = px.bar(fig_data, x=x_col, y=y_col, color=color_col, title=title)
|
| 241 |
+
elif agg_func == "Count":
|
| 242 |
+
fig = px.histogram(df, x=x_col, color=color_col, title=title)
|
| 243 |
+
else: # Median
|
| 244 |
+
fig_data = df.groupby(x_col)[y_col].median().reset_index()
|
| 245 |
+
fig = px.bar(fig_data, x=x_col, y=y_col, color=color_col, title=title)
|
| 246 |
+
|
| 247 |
+
elif selected_plot == "Histogram":
|
| 248 |
+
if not numeric_cols:
|
| 249 |
+
st.warning("No numeric columns available for histogram.")
|
| 250 |
+
else:
|
| 251 |
+
col1, col2 = st.columns(2)
|
| 252 |
+
with col1:
|
| 253 |
+
x_col = st.selectbox("Variable:", numeric_cols)
|
| 254 |
+
with col2:
|
| 255 |
+
nbins = st.slider("Number of bins:", min_value=5, max_value=100, value=30)
|
| 256 |
+
|
| 257 |
+
color_col = st.selectbox("Color by (optional):", [None] + categorical_cols, key="hist_color")
|
| 258 |
+
title = st.text_input("Plot title:", f"Distribution of {x_col}")
|
| 259 |
+
|
| 260 |
+
if st.button("Generate Histogram"):
|
| 261 |
+
fig = px.histogram(df, x=x_col, nbins=nbins, color=color_col, title=title, marginal="box")
|
| 262 |
+
|
| 263 |
+
elif selected_plot == "Box Plot":
|
| 264 |
+
if not numeric_cols:
|
| 265 |
+
st.warning("No numeric columns available for box plot.")
|
| 266 |
+
else:
|
| 267 |
+
col1, col2 = st.columns(2)
|
| 268 |
+
with col1:
|
| 269 |
+
y_col = st.selectbox("Numeric variable:", numeric_cols)
|
| 270 |
+
with col2:
|
| 271 |
+
x_col = st.selectbox("Group by (optional):", [None] + categorical_cols)
|
| 272 |
+
|
| 273 |
+
title = st.text_input("Plot title:", f"Box plot of {y_col}" + (f" by {x_col}" if x_col else ""))
|
| 274 |
+
|
| 275 |
+
if st.button("Generate Box Plot"):
|
| 276 |
+
fig = px.box(df, x=x_col, y=y_col, title=title)
|
| 277 |
+
|
| 278 |
+
elif selected_plot == "Violin Plot":
|
| 279 |
+
if not numeric_cols:
|
| 280 |
+
st.warning("No numeric columns available for violin plot.")
|
| 281 |
+
else:
|
| 282 |
+
col1, col2 = st.columns(2)
|
| 283 |
+
with col1:
|
| 284 |
+
y_col = st.selectbox("Numeric variable:", numeric_cols)
|
| 285 |
+
with col2:
|
| 286 |
+
x_col = st.selectbox("Group by (optional):", [None] + categorical_cols)
|
| 287 |
+
|
| 288 |
+
title = st.text_input("Plot title:", f"Violin plot of {y_col}" + (f" by {x_col}" if x_col else ""))
|
| 289 |
+
|
| 290 |
+
if st.button("Generate Violin Plot"):
|
| 291 |
+
fig = px.violin(df, x=x_col, y=y_col, box=True, points="outliers", title=title)
|
| 292 |
+
|
| 293 |
+
elif selected_plot == "Pie Chart":
|
| 294 |
+
if not categorical_cols:
|
| 295 |
+
st.warning("No categorical columns available for pie chart.")
|
| 296 |
+
else:
|
| 297 |
+
col_to_plot = st.selectbox("Category column:", categorical_cols)
|
| 298 |
+
title = st.text_input("Plot title:", f"Distribution of {col_to_plot}")
|
| 299 |
+
|
| 300 |
+
if st.button("Generate Pie Chart"):
|
| 301 |
+
fig = px.pie(df, names=col_to_plot, title=title)
|
| 302 |
+
|
| 303 |
+
elif selected_plot == "Heatmap (Correlation)":
|
| 304 |
+
if len(numeric_cols) < 2:
|
| 305 |
+
st.warning("Need at least 2 numeric columns for correlation heatmap.")
|
| 306 |
+
else:
|
| 307 |
+
selected_cols = st.multiselect("Select columns for correlation:", numeric_cols, default=numeric_cols[:5] if len(numeric_cols) >= 5 else numeric_cols)
|
| 308 |
+
|
| 309 |
+
if len(selected_cols) < 2:
|
| 310 |
+
st.warning("Please select at least 2 columns.")
|
| 311 |
+
else:
|
| 312 |
+
title = st.text_input("Plot title:", "Correlation Heatmap")
|
| 313 |
+
|
| 314 |
+
if st.button("Generate Heatmap"):
|
| 315 |
+
corr_matrix = df[selected_cols].corr()
|
| 316 |
+
fig = px.imshow(corr_matrix,
|
| 317 |
+
text_auto=".2f",
|
| 318 |
+
aspect="auto",
|
| 319 |
+
title=title,
|
| 320 |
+
color_continuous_scale='RdBu_r',
|
| 321 |
+
labels=dict(color="Correlation"))
|
| 322 |
+
|
| 323 |
+
# Display and download plot
|
| 324 |
+
if fig:
|
| 325 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 326 |
+
|
| 327 |
+
# Download options
|
| 328 |
+
st.subheader("💾 Download Plot")
|
| 329 |
+
col1, col2 = st.columns(2)
|
| 330 |
+
|
| 331 |
+
with col1:
|
| 332 |
+
png_data = fig.to_image(format="png", width=1200, height=800, scale=2)
|
| 333 |
+
st.download_button(
|
| 334 |
+
label="Download as PNG",
|
| 335 |
+
data=png_data,
|
| 336 |
+
file_name="plot.png",
|
| 337 |
+
mime="image/png"
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
with col2:
|
| 341 |
+
html_data = fig.to_html(include_plotlyjs="cdn")
|
| 342 |
+
st.download_button(
|
| 343 |
+
label="Download as HTML",
|
| 344 |
+
data=html_data,
|
| 345 |
+
file_name="plot.html",
|
| 346 |
+
mime="text/html"
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
# === MULTI-PLOT COMPARISON ===
|
| 350 |
+
st.header("⚖️ Compare Multiple Plots")
|
| 351 |
+
|
| 352 |
+
num_plots = st.slider("Number of plots to compare:", min_value=1, max_value=4, value=2)
|
| 353 |
+
|
| 354 |
+
if num_plots > 1:
|
| 355 |
+
fig_compare = make_subplots(
|
| 356 |
+
rows=1, cols=num_plots,
|
| 357 |
+
subplot_titles=[f"Plot {i+1}" for i in range(num_plots)],
|
| 358 |
+
shared_yaxes=False
|
| 359 |
+
)
|
| 360 |
+
|
| 361 |
+
plot_success = True
|
| 362 |
+
|
| 363 |
+
for i in range(num_plots):
|
| 364 |
+
st.markdown(f"### Plot {i+1}")
|
| 365 |
+
plot_type = st.selectbox(f"Plot type:", plot_types, key=f"compare_type_{i}")
|
| 366 |
+
|
| 367 |
+
try:
|
| 368 |
+
if plot_type == "Scatter Plot" and len(numeric_cols) >= 2:
|
| 369 |
+
x_col = st.selectbox(f"X-axis:", numeric_cols, key=f"compare_x_{i}")
|
| 370 |
+
y_col = st.selectbox(f"Y-axis:", [col for col in numeric_cols if col != x_col], key=f"compare_y_{i}")
|
| 371 |
+
trace = go.Scatter(x=df[x_col], y=df[y_col], mode='markers', name=f"{y_col} vs {x_col}")
|
| 372 |
+
fig_compare.add_trace(trace, row=1, col=i+1)
|
| 373 |
+
|
| 374 |
+
elif plot_type == "Histogram" and len(numeric_cols) >= 1:
|
| 375 |
+
x_col = st.selectbox(f"Variable:", numeric_cols, key=f"compare_hist_{i}")
|
| 376 |
+
trace = go.Histogram(x=df[x_col], name=f"Distribution of {x_col}")
|
| 377 |
+
fig_compare.add_trace(trace, row=1, col=i+1)
|
| 378 |
+
|
| 379 |
+
elif plot_type == "Bar Plot" and len(categorical_cols) >= 1 and len(numeric_cols) >= 1:
|
| 380 |
+
x_col = st.selectbox(f"Category:", categorical_cols, key=f"compare_bar_x_{i}")
|
| 381 |
+
y_col = st.selectbox(f"Value:", numeric_cols, key=f"compare_bar_y_{i}")
|
| 382 |
+
trace = go.Bar(x=df[x_col], y=df[y_col], name=f"{y_col} by {x_col}")
|
| 383 |
+
fig_compare.add_trace(trace, row=1, col=i+1)
|
| 384 |
+
|
| 385 |
+
else:
|
| 386 |
+
st.warning(f"Plot {i+1}: Invalid combination for {plot_type}")
|
| 387 |
+
plot_success = False
|
| 388 |
+
|
| 389 |
+
except Exception as e:
|
| 390 |
+
st.error(f"Error in Plot {i+1}: {e}")
|
| 391 |
+
plot_success = False
|
| 392 |
+
|
| 393 |
+
if plot_success and st.button("Generate Comparison Plot"):
|
| 394 |
+
fig_compare.update_layout(height=600, showlegend=True, title_text="Comparison of Multiple Plots")
|
| 395 |
+
st.plotly_chart(fig_compare, use_container_width=True)
|
| 396 |
|
| 397 |
+
# Footer
|
| 398 |
+
st.markdown("---")
|
| 399 |
+
st.caption(f"© {AUTHOR} | License {LICENSE} | Contact: {EMAIL}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|