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

Containerization vs Virtualization: Explore the Difference!

  In today’s world, technology has become an integral part of our daily lives, and the way we work has been greatly revolutionized by the rise of cloud computing. One of the critical aspects of cloud computing is the ability to run applications and services in a virtualized environment. However, with the emergence of new technologies and trends, there are two popular approaches that have emerged, containerization and virtualization, and it can be confusing to understand the difference between the two. In this blog on Containerization vs Virtualization, we’ll explore what virtualization and containerization are, the key difference between virtualization and containerization, and the use cases they are best suited for. By the end of this article, you should have a better understanding of the two technologies and be able to make an informed decision on which one is right for your business needs. Here, we’ll discuss, –  What is Containerization? –  What is Virtualization? – Benefits of Con

Step-by-Step Guide to Cloud Migration With DevOps

This successful adoption of cloud technologies is attributed to scalability, security, faster time to market, and team collaboration benefits it offers. With this number increasing rapidly among companies at all levels, organizations are  looking forward to the methods that help them: Eliminate platform complexities Reduce information leakage Minimize cloud operation costs To materialize these elements, organizations are actively turning to DevOps culture that helps them integrate development and operations processes to automate and optimize the complete software development lifecycle. In this blog post, we will discuss the step-by-step approach to cloud migration with DevOps. Steps to Perform Cloud Migration With DevOps Approach Automation, teamwork, and ongoing feedback are all facilitated by the DevOps culture in the cloud migration process. This translates into cloud environments that are continuously optimized to support your business goals and enable faster, more seamless migrat

Migration Of MS SQL From Azure VM To Amazon RDS

The MongoDB operator is a custom CRD-based operator inside Kubernetes to create, manage, and auto-heal MongoDB setup. It helps in providing different types of MongoDB setup on Kubernetes like-  standalone, replicated, and sharded.  There are quite amazing features we have introduced inside the operator and some are in-pipeline on which deployment is going on. Some of the MongoDB operator features are:- Standalone and replicated cluster setup Failover and recovery of MongoDB nodes Inbuilt monitoring support for Prometheus using MongoDB Exporter. Different Kubernetes-related best practices like:- Affinity, Pod Disruption Budget, Resource management, etc, are also part of it. Insightful and detailed monitoring dashboards for Grafana. Custom MongoDB configuration support. [Good Read:  Migration Of MS SQL From Azure VM To Amazon RDS  ] Other than this, there are a lot of features are in the backlog on which active development is happening. For example:- Backup and Restore support TLS encryp