Deploy Streamlit or Dash
Posit Connect Cloud supports many kinds of frameworks. All you need is a requirements.txt
so Connect Cloud can build the environment.
We will build and deploy the same application as we did in the Shiny Express Lab
#| '!! shinylive warning !!': |
#| shinylive does not work in self-contained HTML documents.
#| Please set `embed-resources: false` in your metadata.
#| standalone: true
#| components: [editor, viewer]
#| layout: horizontal
#| viewerHeight: 500
from palmerpenguins import load_penguins
from plotnine import aes, geom_histogram, ggplot, theme_minimal
from shiny.express import input, render, ui
dat = load_penguins()
species = dat["species"].unique().tolist()
ui.input_radio_buttons("species", "Species", species, inline=True)
@render.plot
def plot():
sel = dat[dat["species"] == input.species()]
return (
ggplot(aes(x="bill_length_mm"))
+ geom_histogram(dat, fill="#C2C2C4", binwidth=1)
+ geom_histogram(sel, fill="#447099", binwidth=1)
+ theme_minimal()
)
Before you begin
Posit Connect Cloud deploys applications in a GitHub repository, make sure you have a GitHub repository set up to put the code we will use for this lab. You can do this lab completely within the web interface.
Then create the requirements.txt
file.
requirements.txt
dash
plotly
pandas
palmerpenguins
plotnine
streamlit
Streamlit
Here’s an example Streamlit application. Save it to an app.py
file. You can check out the Connect Cloud documentation to learn more about deploying Streamlit applicaitons to Connect Cloud
app.py
import streamlit as st
from palmerpenguins import load_penguins
from plotnine import aes, geom_histogram, ggplot, theme_minimal
import matplotlib.pyplot as plt
# Load the data
= load_penguins()
dat = dat["species"].unique().tolist()
species
# Add radio button widget
= st.radio("Species", species, horizontal=True)
selected_species
# Filter data based on selection
= dat[dat["species"] == selected_species]
sel
# Create plot
= (
plot ="bill_length_mm"))
ggplot(aes(x+ geom_histogram(dat, fill="#C2C2C4", binwidth=1)
+ geom_histogram(sel, fill="#447099", binwidth=1)
+ theme_minimal()
)
# Display the plot
st.pyplot(ggplot.draw(plot))
Dash
Here’s an example Dash application. Save this to an app.py
file. You can check out the Connect Cloud documentation to learn more about deploying Dash applications to Connect Cloud
app.py
import dash
from dash import dcc, html
from dash.dependencies import Input, Output
import plotly.express as px
import plotly.graph_objects as go
from palmerpenguins import load_penguins
# Initialize the Dash app
= dash.Dash(__name__)
app
# Load the data
= load_penguins()
dat = dat["species"].unique().tolist()
species
# Define the layout
= html.Div([
app.layout "Palmer Penguins Bill Length"),
html.H1(
# Radio buttons for species selection
html.Div(["Species:"),
html.Label(
dcc.RadioItems(id='species-radio',
=[{'label': s, 'value': s} for s in species],
options=species[0],
value=True
inline
)
]),
# Graph container
id='histogram-plot')
dcc.Graph(
])
# Callback to update the plot based on species selection
@app.callback(
'histogram-plot', 'figure'),
Output('species-radio', 'value')
Input(
)def update_plot(selected_species):
# Create two histogram traces
# 1. All penguins (light gray)
= go.Histogram(
all_penguins =dat["bill_length_mm"].dropna(),
x=dict(size=1),
xbins='#C2C2C4',
marker_color='All Penguins'
name
)
# 2. Selected species (blue)
= dat[dat["species"] == selected_species]
sel = go.Histogram(
selected_penguins =sel["bill_length_mm"].dropna(),
x=dict(size=1),
xbins='#447099',
marker_color=f'{selected_species}'
name
)
# Create the figure
= go.Figure(data=[all_penguins, selected_penguins])
fig
# Update layout
fig.update_layout(=f'Bill Length Distribution',
title='Bill Length (mm)',
xaxis_title='Count',
yaxis_title='overlay',
barmode='plotly_white',
template=False
showlegend
)
return fig
# Run the app
if __name__ == '__main__':
app.run()
Here’s a version that uses plotnine
app.py
from palmerpenguins import load_penguins
# Set matplotlib backend to non-GUI 'Agg' before importing plotnine
# Matplotlib is trying to create GUI elements outside the main thread, which is not allowed on macOS.
# common issue when using plotting libraries that rely on Matplotlib in threaded web applications
import matplotlib
'Agg')
matplotlib.use(from plotnine import aes, geom_histogram, ggplot, theme_minimal
import dash
from dash import dcc, html, Input, Output
import plotly.graph_objects as go
from io import BytesIO
import base64
# Load the data
= load_penguins()
dat = dat["species"].unique().tolist()
species
# Initialize the Dash app
= dash.Dash(__name__)
app
# Define the layout
= html.Div([
app.layout "Palmer Penguins"),
html.H1(
# Radio buttons for species selection
html.Div(["Species"),
html.Label(
dcc.RadioItems(id="species",
=[{"label": s, "value": s} for s in species],
options=species[0], # Default to first species
value=True
inline
)
]),
# Image component to display the plotnine plot
id='plot-image')
html.Img(
])
# Define callback to update the plot based on species selection
@app.callback(
'plot-image', 'src'),
Output('species', 'value')
Input(
)def update_plot(selected_species):
# Filter data for selected species
= dat[dat["species"] == selected_species]
sel
# Create the plotnine plot
= (
plot ="bill_length_mm"))
ggplot(aes(x+ geom_histogram(dat, fill="#C2C2C4", binwidth=1)
+ geom_histogram(sel, fill="#447099", binwidth=1)
+ theme_minimal()
)
# Save the plot to a BytesIO object
= BytesIO()
img_buffer format="png", dpi=100, width=8, height=6, units="in")
plot.save(img_buffer, 0)
img_buffer.seek(
# Convert to base64 for displaying in the Dash app
= base64.b64encode(img_buffer.read()).decode()
img_str
return f'data:image/png;base64,{img_str}'
# Run the app
if __name__ == '__main__':
app.run()
Deploy
We’ll be deploying our shiny application to Connect Cloud. Here are the steps to publish your application.
- Click the Publish icon button on the top of your Portfolio page
- Select Shiny
- Select the public repository that you created in this tutorial
- Confirm the branch
- Select
app.py
as the primary file - Click Publish
Publishing will display status updates during the deployment process. You will also find build logs streaming on the lower part of the screen.
Congratulations! You successfully deployed to Connect Cloud and are now able to share the link with others.
Redeploy
If you update the code to your application or the underlying data source, commit and push the changes to your GitHub repository.
Once the repository has the updated code, you can republish the application on Connect Cloud by going to your Content List and clicking the republish icon.