Skip to main content

Getting Started with StreamLit: Build Interactive Data Apps in Python

Streamlit is an open-source Python library that simplifies the creation of interactive web apps for data science and machine learning projects. It is highly user-friendly, with minimal coding required to turn Python scripts into shareable web apps. It allows developers and data scientists to create interactive, visually appealing applications with minimal effort by focusing on writing Python code rather than dealing with front-end development. 

KEY FEATURES

    • Simplicity: You can build apps using just Python. There’s no need for HTML, CSS, or JavaScript. 
    • Fast Development: With a few lines of code, you can create dashboards or web apps that automatically update as the Python script changes. 
    • Interactive Widgets: Streamlit provides a range of widgets (e.g., sliders, buttons, textboxes) that make it easy to add interactivity to your app. 
    • Data Visualizations: It integrates seamlessly with popular data visualization libraries like Matplotlib, Plotly, and Seaborn, allowing you to display graphs and charts effortlessly. 
    • Live Updates: Streamlit apps can dynamically update in real time as data or inputs change. 
    • Deployment: You can easily deploy Streamlit apps on platforms like Streamlit Cloud, AWSGCP or any other cloud service. 

BUILD YOUR FIRST STREAMLIT APP 

The primary objective of this Streamlit app is to provide an intuitive and interactive visualization of crime rates across major cities in India. By leveraging real-time data visualization tools, this application aims to provide users with insights into the varying crime rates in different urban areas.  The data used in this app is sample data, designed to illustrate the functionality and capabilities of the application. You are encouraged to replace this sample dataset with your own real-time data to create tailored visualizations that reflect the most relevant information.  1. Set up your python development environment. 2. Installation:  

pip install streamlit pandas plotly

3. You can validate your Streamlit Installation by running the Hello app 

Streamlit hello

4. Create a crime_rates.py file and import necessary libraries as per the code snippet mentioned below 

import streamlit as st
import pandas as pd
import plotly.graph_objects as go

# sample data 
data = { 
'City': ['Mumbai', 'Delhi', 'Bangalore', 'Hyderabad', 'Kolkata', 'Chennai', 'Ahmedabad', 'Pune', 'Jaipur', 'Lucknow'], 
'Crime Rate': [105, 98, 75, 85, 88, 65, 80, 70, 82, 68], # Crime rates per 100k people (mock data) 
'Latitude': [19.0760, 28.7041, 12.9716, 17.3850, 22.5726, 13.0827, 23.0225, 18.5204, 26.9124, 26.8467], 
'Longitude': [72.8777, 77.1025, 77.5946, 78.4867, 88.3639, 80.2707, 72.5714, 73.8567, 75.7873, 80.9462] 
}

# Create a DataFrame
df = pd.DataFrame(data)

#size of the datapoint
marker_size = df['Crime Rate'] / max(df['Crime Rate']) * 20

# Streamlit App
st.title("Crime Rates Across Indian Cities")

# Show the DataFrame
st.write("Here is the crime rate data for various cities in India:")
st.dataframe(df)

fig = go.Figure(go.Scattermapbox(
lat=df['Latitude'],
lon=df['Longitude'],
mode='markers',
marker=go.scattermapbox.Marker(
size=marker_size, # Adjust size of the markers dynamically based on
crime rate
color='red', # Set the color of the points
opacity=0.7 # Make the points slightly transparent for better
visualization
), 

text=df['City'] + '<br>Crime Rate: ' + df['Crime Rate'].astype(str) + ' per 100k people',
hoverinfo='text'
))

# Set the layout for the map
fig.update_layout(
mapbox=dict(
style='open-street-map',
zoom=4,
center=dict(lat=20.5937, lon=78.9629) # Center of India
),
margin={"r":0,"t":0,"l":0,"b":0} # Remove margins
)

# Display the Plotly map in Streamlitst.plotly_chart(fig)

5. Navigate to the directory where your Python file is saved, and run the following command: 

streamlit run crime_rates.py 

In this app, Streamlit is utilized to create an intuitive and engaging user experience. 

    • Title Creation: The st.title() function establishes a clear and prominent title, immediately informing users about the app’s focus on crime rates across Indian cities. 
    • Context and Description: The st.write() function provides essential context and descriptions, guiding users through the data displayed in the app. 
    • Data Presentation: Streamlit’s st.dataframe() function presents the underlying crime rate data in a well-structured, scrollable table, making it easy for users to explore and compare crime rates among cities. 
    • Interactive Visualization: Finally, the app employs Plotly mapping features supported by Streamlit, enabling the interactive display of a scatter map. Users can hover over the markers to view detailed information about each city, including the specific crime rate. 

Through these features, Streamlit effectively enhances the app’s usability, allowing users to interact with and understand crime data in a visually appealing manner. 

[ Good Read: Data Privacy ]

APP PREVIEW

Once the app is running, you will see an interactive map displaying crime rates across various Indian cities, accompanied by a detailed table of the underlying data.  Users can hover over the markers on the map to view specific crime rates, making it easy to explore and analyze urban safety trends. 

You can check more info about: StreamLit.

Comments

Popular posts from this blog

How to Perform Penetration Testing on IoT Devices: Tools & Techniques for Business Security

The Internet of Things (IoT) has transformed our homes and workplaces but at what cost?   With billions of connected devices, hackers have more entry points than ever. IoT penetration testing is your best defense, uncovering vulnerabilities before cybercriminals do. But where do you start? Discover the top tools, techniques, and expert strategies to safeguard your IoT ecosystem. Don’t wait for a breach, stay one step ahead.   Read on to fortify your devices now!  Why IoT Penetration Testing is Critical  IoT devices often lack robust security by design. Many run on outdated firmware, use default credentials, or have unsecured communication channels. A single vulnerable device can expose an entire network.  Real-world examples of IoT vulnerabilities:   Mirai Botnet (2016) : Exploited default credentials in IP cameras and DVRs, launching massive DDoS attacks. Stuxnet (2010): Targeted industrial IoT systems, causing physical damage to nuclear centrifu...

Infrastructure-as-Prompt: How GenAI Is Revolutionizing Cloud Automation

Forget YAML sprawl and CLI incantations. The next frontier in cloud automation isn't about writing more code; it's about telling the cloud what you need. Welcome to the era of Infrastructure-as-Prompt (IaP), where Generative AI is transforming how we provision, manage, and optimize cloud resources. The Problem: IaC's Complexity Ceiling Infrastructure-as-Code (IaC) like Terraform, CloudFormation, or ARM templates revolutionized cloud ops. But it comes with baggage: Steep Learning Curve:  Mastering domain-specific languages and cloud provider nuances takes time. Boilerplate Bloat:  Simple tasks often require verbose, repetitive code. Error-Prone:  Manual coding leads to misconfigurations, security gaps, and drift. Maintenance Overhead:  Keeping templates updated across environments and providers is tedious. The Solution: GenAI as Your Cloud Co-Pilot GenAI models (like GPT-4, Claude, Gemini, or specialized cloud models) understand n...

How Security-First CI/CD Pipelines Help Mitigate Business Risk

Businesses today must adapt quickly, rolling out software updates and new features at an unprecedented pace. To accomplish this, many turn to Continuous Integration and Continuous Delivery (CI/CD) pipelines. However, this pursuit of speed can introduce significant security risks if it's not approached with caution. This is where the concept of DevSecOps comes into play. It’s an essential strategy for organizations aiming to strike the right balance between speed and security. Historically, security has often been an afterthought, resulting in delays and making systems more vulnerable to cyber threats. DevSecOps changes this narrative by embedding security practices within every stage of the software development lifecycle. In this blog, we will delve into the tangible ROI of adopting DevSecOps , highlighting how a security-first mindset in CI/CD not only minimizes business risks but also reduces downtime and leads to measurable cost savings. Additionally, we’ll examine how automatin...