top of page
Writer's pictureLena Bharathi

Getting Started with Streamlit

Streamlit is an open-source Python library that allows developers and data scientists to quickly and easily create web applications and interactive data dashboards. It was designed to simplify the process of turning data scripts into shareable web apps, requiring minimal effort and coding.

Key features and characteristics of Streamlit include:

  1. Simplicity: Streamlit is known for its simple and intuitive API. You can create web apps using a Python script and plain Python commands, making it accessible to individuals with various levels of programming experience.

  2. Rapid Prototyping: It enables rapid prototyping and development of data-driven applications. With a few lines of code, you can create interactive elements like charts, tables, sliders, and text inputs.

  3. Interactive Widgets: Streamlit provides a wide range of widgets that you can use to interact with your data and customize your app. These widgets include buttons, sliders, text inputs, and more.

  4. Real-time Updates: Streamlit apps update in real-time as you modify the code. This makes it easy to experiment with different visualizations and data without restarting the application.

  5. Data Visualization: You can integrate popular data visualization libraries like Matplotlib, Plotly, and Altair to create interactive charts and graphs in your Streamlit apps.

  6. Customization: While Streamlit is simple to use out of the box, it also allows for customization. You can style your app, add custom CSS, and create more complex layouts when needed.

  7. Deployment Options: Streamlit offers various deployment options, from sharing your app locally to deploying it on cloud platforms like Heroku, AWS, or Streamlit Sharing. This makes it convenient for sharing your work with others.

  8. Community and Ecosystem: Streamlit has a growing and active community of users and developers. There is a repository of custom components, templates, and extensions created by the community to enhance Streamlit's capabilities.

Streamlit is particularly popular among data scientists and engineers for creating quick prototypes, sharing data insights, and building data dashboards. It has gained popularity in the data science and machine learning communities for its ability to create interactive apps to showcase models and data analyses.

To install Streamlit using Anaconda:

To install Streamlit using Anaconda, you can create a new conda environment and then install Streamlit within that environment. Here are the steps to do this:

  1. Open Anaconda Navigator (GUI):

    • Open Anaconda Navigator from your system's applications or by searching for it.

  2. Create a New Conda Environment:

    • Click on the "Environments" tab on the left-hand side of Anaconda Navigator.

    • Click the "Create" button to create a new environment.

    • Give your new environment a name (e.g., "streamlit_env").

    • Choose the Python version you want to use. Streamlit typically works well with Python 3.6 or later.

    • Click the "Create" button to create the environment.

  3. Activate the New Environment:

    • After creating the environment, select it from the list of environments in Anaconda Navigator.

    • Click the "Play" (▶) button next to the environment name to activate it. This opens a terminal within the environment.

  4. Install Streamlit within the Environment:

    • In the terminal that opened within the activated environment, run the following command to install Streamlit using pip:

pip install streamlit

  1. This will install Streamlit and its dependencies into the selected environment.

  2. Verify the Installation:

You can verify that Streamlit was successfully installed by running:

streamlit --version

This command should display the version of Streamlit, indicating that the installation was successful.

  1. Create and Run a Streamlit App:

    • Create a new Python script (e.g., my_app.py) or use an existing one to build your Streamlit app.

    • Write the Streamlit app code in your script.

    • To run your Streamlit app, activate the environment by using the "Play" button in Anaconda Navigator or by running conda activate streamlit_env in the terminal. Then, navigate to the directory containing your Python script and use the streamlit run command:

streamlit run my_app.py

  1. Replace my_app.py with the name of your Python script.

Your Streamlit app should now be running in your browser, and you can access it via the provided local URL (usually http://localhost:8501).

By following these steps, you'll have Streamlit installed and running within a dedicated Anaconda environment, ensuring better isolation of packages for your project.


How to work with streamlit:


1.Import streamlit library


import streamlit as st


2.Write anything into streamlit


2a)Display Text:


st.write('Hello, *World!* :sunglasses:')


2b) Display Dataframe:


df = pd.DataFrame(

np.random.randn(200, 3),

columns=['a', 'b', 'c'])

st.write(df)


2c)Display charts:

import altair as alt

df = pd.DataFrame(np.random.randn(200,3),columns=['a', 'b', 'c'])

c = alt.Chart(df).mark_circle().encode(x='a', y='b', size='c', color='c', tooltip=['a', 'b', 'c'])

st.write(c)

3.Display Title:

st.title('This is a title')

4.Display Header:

st.header('This is a header with a divider', divider='rainbow')

5.Display charts:

chart_data = pd.DataFrame(np.random.randn(20, 3), columns=["a", "b", "c"])

st.line_chart(chart_data)

6.Display Scatter:

import streamlit as st

chart_data = pd.DataFrame(np.random.randn(20, 4), columns=["col1", "col2", "col3", "col4"])

st.scatter_chart(chart_data,x='col1',y=['col2', 'col3'],size='col4',

color=['#FF0000', '#0000FF'], # Optional)

7.Display pyplot charts:

arr = np.random.normal(1, 1, size=100)

fig, ax = plt.subplots()

ax.hist(arr, bins=20)

st.pyplot(fig)

8.Display bokeh chart:

import streamlit as st

from bokeh.plotting import figure

x = [1, 2, 3, 4, 5]

y = [6, 7, 2, 4, 5]

p = figure(title='simple line example',x_axis_label='x',

y_axis_label='y')

p.line(x, y, legend_label='Trend', line_width=2)

st.bokeh_chart(p, use_container_width=True)

9.Display Image:

image = Image.open('sunrise.jpg')

st.image(image, caption='Sunrise by the mountains')


Layouts and Containers

10.Partition by sidebar: Divide the streamlit window into sidebar

with st.sidebar:

with st.echo():

st.write("This code will be printed to the sidebar.")


with st.spinner("Loading..."):

time.sleep(5)

st.success("Done!")

11.Partition into columns:

Divide the streamlit window into 3 different columns

col1, col2, col3 = st.columns(3)

with col1:

st.header("A cat")

st.image("https://static.streamlit.io/examples/cat.jpg")

with col2:

st.header("A dog")

st.image("https://static.streamlit.io/examples/dog.jpg")

with col3:

st.header("An owl")

st.image("https://static.streamlit.io/examples/owl.jpg")

12. Expander

Expands the window

with st.expander("See explanation"):

st.write(\"\"\"

The chart above shows some numbers I picked for you.

I rolled actual dice for these, so they're *guaranteed* to

be random.

\"\"\")

st.image("https://static.streamlit.io/examples/dice.jpg")

13. Stops execution immediately

Streamlit will not run any statements after st.stop().

name = st.text_input('Name')

if not name:

st.warning('Please input a name.')

st.stop()

st.success('Thank you for inputting a name.')


Streamlit For DataAnalyst:

Streamlit is an excellent choice for data analysts who want to create interactive and data-driven web applications to showcase their data analysis work. Streamlit's simplicity and Pythonic approach make it accessible and efficient for data professionals. Here are some ways data analysts can use Streamlit:


1. **Data Visualization**: Data analysts can create interactive data visualizations with Streamlit using libraries like Matplotlib, Plotly, or Altair. You can display charts, graphs, and plots to illustrate your data analysis results.


2. **Data Exploration**: Streamlit allows you to build interactive dashboards for exploring datasets. You can add widgets like sliders, input boxes, and buttons to filter and explore data dynamically.


3. **Data Summarization**: Streamlit makes it easy to display summary statistics and key insights from your data. You can use `st.write()` to display text-based summaries or tables of descriptive statistics.


4. **Machine Learning Prototyping**: Data analysts can quickly prototype machine learning models and showcase their results with Streamlit. You can create web apps to demonstrate the effectiveness of different algorithms, model parameters, and datasets.


5. **Interactive Reports**: Instead of static reports, data analysts can build interactive reports using Streamlit. You can embed data visualizations, tables, and interactive elements directly into your reports.


6. **Data Import and Export**: Streamlit can handle data loading and exporting tasks. You can add file upload widgets to allow users to upload their datasets and export analysis results.


7. **Sharing Insights**: Streamlit apps can be easily shared with others. You can deploy your Streamlit apps on platforms like Streamlit Sharing, Heroku, or AWS to share your data analysis findings with colleagues or the broader community.


Here's a simple example of a Streamlit app that a data analyst might create to display a scatter plot:


```python

import streamlit as st

import pandas as pd

import matplotlib.pyplot as plt


# Load sample data

data = pd.read_csv('sample_data.csv')


# Set app title

st.title('Data Analysis with Streamlit')


# Display data

st.write(data)


# Create a scatter plot

fig, ax = plt.subplots()

ax.scatter(data['X'], data['Y'])

ax.set_xlabel('X')

ax.set_ylabel('Y')

st.pyplot(fig)

```


In this example, the Streamlit app loads a CSV dataset, displays the data in a table, and creates a scatter plot of the data. Data analysts can use Streamlit's widgets and interactive capabilities to customize and explore the data further.

Streamlit provides a wide range of customization options and integrations with various data science libraries, making it a versatile tool for data analysts to showcase their work and share insights with stakeholders.

201 views

Recent Posts

See All
bottom of page