How to Build a Simple Statistical App in Streamlit

How to Build a Simple Statistical App in Streamlit
Image by Author | Canva

In this article, you’ll learn how to build a powerful statistical app using Streamlit. If you’re new to it, Streamlit is an open-source Python framework that helps you turn data scripts into interactive web apps in minutes. That’s right! No frontend skills needed. You can read more about it in the official docs.

The app we’ll build won’t just show basic stats like mean and median; that’s too easy. Instead, we’ll create a more advanced tool that loads a CSV dataset and allows users to explore descriptive statistics, correlation heatmaps, and distribution plots, with options to filter data by column types, select variables, and even compare multiple variables visually. It’s the kind of tool you could actually reuse in real projects or data analysis workflows.

Prerequisites

Before we start building the app, let’s talk about the tools and libraries we’ll be using and why they’re needed:

  • Streamlit: The main framework we’ll use to build and run the app, handling the UI and interactivity
  • Pandas: We will make use of Pandas for handling and manipulating the data we’ll be analyzing
  • NumPy: This is helpful for numerical operations behind the scenes
  • Seaborn and Matplotlib: These are popular plotting libraries we’ll use to visualize distributions and correlations
  • Scikit-learn: We’ll use it for some built-in statistical functions like variance and scaling (optional but handy)

To install everything at once, just run:

pip install streamlit pandas numpy seaborn matplotlib scikit-learn

Once that’s done, you’re ready to dive into building the app.

Building The Statistical App in Streamlit

We’ll break this project into logical steps, so it’s easy to follow and extend later. Here’s the flow of the app:

  • Set up the app structure
  • File upload and basic data display
  • Perform descriptive statistical analysis
  • Generate visualizations
  • Provide downloadable results

Step 1: Basic App Setup and Title

First, we’ll import the necessary libraries and set the title of our Streamlit app. We set the page layout and title, and give users a quick intro on what to do.

# streamlit_app.py
import streamlit as st
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from io import BytesIO
from sklearn.preprocessing import StandardScaler
import base64

# Set the page config
st.set_page_config(page_title="Statistical Analyzer", layout="wide")

# App Title
st.title("📊 Simple Statistical Analysis App")
st.markdown("Upload your dataset and get quick statistical insights and visualizations.")

Step 2: Upload and Preview Dataset

Let’s allow users to upload a CSV file or dataset, and then we immediately show a preview of the top 5 rows using st.dataframe.

# File uploader
uploaded_file = st.file_uploader("Upload a CSV file", type=["csv"])

if uploaded_file is not None:
    # Read CSV file
    df = pd.read_csv(uploaded_file)

    st.subheader("📄 Preview of Uploaded Data")
    st.dataframe(df.head())

Step 3: Show Basic Statistics

We’ll show descriptive stats like mean, median, mode, and standard deviation.

    st.subheader("📈 Descriptive Statistics")

    numeric_cols = df.select_dtypes(include=np.number).columns.tolist()

    if numeric_cols:
        selected_cols = st.multiselect("Select numerical columns", numeric_cols, default=numeric_cols)

        if selected_cols:
            stats = df[selected_cols].describe().T
            stats["mode"] = df[selected_cols].mode().iloc[0]

            st.dataframe(stats)
        else:
            st.warning("Please select at least one column.")
    else:
        st.error("No numerical columns found in the dataset.")

This code helps users choose which numeric columns they want to analyze, then calculates basic statistics and shows them in a nice table.

Step 4: Visualize Distributions and Correlations

Let’s visualize how data is spread using a histogram and how numeric variables relate to each other using a correlation heatmap.

    st.subheader("📊 Visualizations")

    # Histogram
    st.markdown("**Distribution Histogram**")
    col_to_plot = st.selectbox("Select column for histogram", selected_cols)

    fig, ax = plt.subplots()
    sns.histplot(df[col_to_plot], kde=True, ax=ax)
    st.pyplot(fig)

    # Correlation heatmap
    st.markdown("**Correlation Heatmap**")
    corr = df[selected_cols].corr()

    fig2, ax2 = plt.subplots(figsize=(10, 6))
    sns.heatmap(corr, annot=True, cmap="coolwarm", ax=ax2)
    st.pyplot(fig2)

Step 5: Standardize and Download Data

We’ll add a feature to scale numeric columns using StandardScaler, and then allow users to download the processed CSV.

    st.subheader("📦 Optional: Standardize Numerical Features")

    if st.checkbox("Standardize data using StandardScaler"):
        scaler = StandardScaler()
        df_scaled = df.copy()
        df_scaled[selected_cols] = scaler.fit_transform(df[selected_cols])

        st.write("Standardized Data Preview")
        st.dataframe(df_scaled.head())

        # Convert to CSV
        def convert_df(df):
            return df.to_csv(index=False).encode('utf-8')

        csv = convert_df(df_scaled)
        st.download_button("Download Scaled Data", csv, "scaled_data.csv", "text/csv")

Running the App

You can run this app locally using:

    streamlit run streamlit_app.py

If everything is set up correctly, you’ll get a slick UI in your browser with upload, stats, plots, and download options.

Statistical Analysis App Dashboard
Statistical Analysis App Dashboard

Here is what the dashboard looks like after a dataset has been uploaded.

Full App Dashboard
Full App Dashboard

Takeaways

In this article, we built a simple but powerful statistical app using Streamlit. It lets you upload a CSV file, explore the data, check basic stats, visualize distributions and correlations, and even download a scaled version of your dataset.

You can extend the app by adding more statistical features, like outlier detection, hypothesis testing, or interactive plots with Plotly. Feel free to experiment, tweak the interface, or use it as a base for your own data analysis tool. The goal is to learn by building, so keep exploring.

Leave a Reply

Your email address will not be published. Required fields are marked *