Basic Introduction to Streamlit
<span>Streamlit</span>
is an open-source Python library for quickly building shareable data applications. It allows data scientists and researchers to easily create interactive web applications without deep knowledge of web development.
Features
-
Easy to Use: Quickly start and run applications with a simple API. -
Interactivity: Easily add interactive elements like buttons, sliders, etc. -
Data Visualization: Supports various chart libraries like Matplotlib, Altair, etc. -
Caching: Smart caching features to improve application performance. -
Easy Deployment: One-click deployment to shared servers or your own server.
How to Install Streamlit
Installing<span>Streamlit</span>
is very simple; you just need to run the following command in your command line interface:
pip install streamlit
Once installed, you can import<span>Streamlit</span>
in your Python script like this:
import streamlit as st
This completes the installation and import of<span>Streamlit</span>
, and you can start using it to build your interactive applications.
Streamlit’s Functional Features
<span>Streamlit</span>
is an open-source Python library for quickly building shareable machine learning models and data analysis applications.
Features
-
Easy to Use: Build powerful web applications with very little code. -
Strong Interactivity: Easily add interactive elements to enhance user experience. -
Automatic Updates: Application content updates automatically after code changes. -
Supports Various Data Formats: Seamless integration with various data sources and formats. -
Rich Plugins: The community provides a wealth of plugins to extend application functionality.
Basic Functions of Streamlit
Creating a Basic Interactive Interface
Using<span>st.title</span>
and <span>st.text</span>
functions, we can easily create a basic interactive interface.
import streamlit as st
# Set title
st.title('Welcome to Streamlit!')
# Add text
st.text('This is a simple Streamlit app.')
Input Data
<span>st.text_input</span>
function allows users to input text data, which is very useful for creating interactive applications.
# User input
user_input = st.text_input('Please enter your name:')
st.write('Hello, ', user_input)
Display Data
Using<span>st.write</span>
, you can easily display text, data, and charts.
# Display data
st.write('Here is a list of items:')
st.write([1, 2, 3, 4, 5])
Using DataFrame
If you are working with a Pandas DataFrame,<span>st.dataframe</span>
can help you easily display it.
import pandas as pd
# Create DataFrame
df = pd.DataFrame({
'first column': [1, 2, 3, 4],
'second column': [10, 20, 30, 40]
})
# Display DataFrame
st.dataframe(df)
File Upload
Streamlit allows users to upload files, which is very useful for data processing and analysis applications.
# File upload
uploaded_file = st.file_uploader("Choose a file")
if uploaded_file is not None:
# Read file content
data = uploaded_file.read()
st.write(data)
Using Charts
Streamlit supports various chart libraries like Matplotlib and Altair, making it easy to integrate charts.
import matplotlib.pyplot as plt
# Create chart
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [1, 4, 9, 16])
# Display chart
st.pyplot(fig)
The following is the content of the basic functions section, covering some core usages of Streamlit, providing programmers with a quick start guide.
Advanced Features of Streamlit
1. Caching
Utilizing caching can speed up the operation of data-intensive applications.
import streamlit as st
import pandas as pd
@st.cache
def load_data():
return pd.read_csv('data.csv')
data = load_data()
st.write(data)
2. Interactive Widgets
Enhance user interaction with the application using interactive widgets.
import streamlit as st
option = st.selectbox(
'Select an option',
('Option A', 'Option B', 'Option C')
)
'You selected:', option
3. Data Visualization
Combine with third-party libraries to achieve rich data visualization effects.
import streamlit as st
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.figure()
plt.plot(x, y)
st.pyplot(plt)
4. Multi-Page Applications
Create multi-page applications for modular management of complex functionalities.
import streamlit as st
def main():
menu = ["Home", "About"]
choice = st.sidebar.selectbox("Select a page", menu)
if choice == "Home":
st.write("This is the home page")
elif choice == "About":
st.write("This is the about page")
if __name__ == "__main__":
main()
5. Custom Themes
Customize<span>Streamlit</span>
themes to meet personalized needs.
import streamlit as st
st.markdown("""
<style>
.main {
color: blue;
}
</style>
""", unsafe_allow_html=True)
st.markdown('<p class="main">This is custom themed text</p>', unsafe_allow_html=True)
Practical Application Scenarios of Streamlit
Data Visualization Reports
In data analysis and visualization,<span>Streamlit</span>
provides a concise interface to easily create interactive reports. Below is an example of using<span>Streamlit</span>
and<span>pandas</span>
to generate a data report:
import streamlit as st
import pandas as pd
# Load data
data = pd.read_csv('data.csv')
# Display data
st.write(data)
# Select column
selected_column = st.selectbox('Select a column for visualization', data.columns.tolist())
# Draw chart
st.line_chart(data[selected_column])
Machine Learning Model Deployment
<span>Streamlit</span>
can help developers quickly deploy machine learning models for online predictions. Below is a simple deployment example:
import streamlit as st
from sklearn.externals import joblib
# Load model
model = joblib.load('model.pkl')
# Input features
feature1 = st.number_input('Input feature 1')
feature2 = st.number_input('Input feature 2')
# Prediction
if st.button('Predict'):
prediction = model.predict([[feature1, feature2]])
st.write('Prediction result:', prediction)
Interactive Web Applications
Using<span>Streamlit</span>
, you can quickly build interactive web applications. Below is a simple online calculator example:
import streamlit as st
# Calculator function
def calculate(operation, num1, num2):
if operation == '+':
return num1 + num2
elif operation == '-':
return num1 - num2
elif operation == '*':
return num1 * num2
elif operation == '/':
return num1 / num2
# User input
num1 = st.number_input('Input number 1')
num2 = st.number_input('Input number 2')
operation = st.selectbox('Select an operator', ['+', '-', '*', '/'])
# Calculate and display result
if st.button('Calculate'):
result = calculate(operation, num1, num2)
st.write('Result:', result)
The following is a detailed content of these three application scenarios:
Data Visualization Reports
This scenario demonstrates how to use<span>Streamlit</span>
to quickly create an interactive data report, which is very useful for data analysts.
Machine Learning Model Deployment
In this scenario, we see how to deploy a trained machine learning model using<span>Streamlit</span>
to provide online prediction functionality.
Interactive Web Applications
Finally, this scenario illustrates<span>Streamlit</span>
‘s powerful capability in building simple interactive web applications, making it very suitable for rapid prototyping.
Conclusion
<span>Streamlit</span>
has become the tool of choice for data scientists and developers due to its simplicity and powerful functionality. Through this article, you should be able to use<span>Streamlit</span>
to quickly build interactive applications. Continuously exploring and discovering<span>Streamlit</span>
‘s advanced features will help you take your projects to the next level.