Skip to content
9 changes: 5 additions & 4 deletions docs/apps/TemplateMatplotlib/app.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,13 @@ hide:
---

# Matplotlib Template
Quick example for a simple matplotlib app. Matplotlib is a popular Python library that can be used to create plots.
Quick example for a simple matplotlib app. Matplotlib is a popular Python library that can be used to create plots. It is most suited for static plots, but can also be coerced to create animations.
<!-- more -->
This is a simple example to showcase different matplotlib apps using Shiny for Python.
## Simplest matplotlib plot
{{embed_app("100%", "500px", "automatic")}}
The following example demonstrates how to create a simple static plot using Matplotlib within a Shiny app.
{{embed_app("100%", "500px", "static")}}
This is the most straightforward way to integrate plots into your tools by leveraging matplotlib's vast capabilities for visualizations.
## Animations using matplotlib
While it is in principle possible to create animations using Matplotlib in Shiny for Python, it requires some additional setup compared to static plots. The following example demonstrates how to create an animated plot using Matplotlib within a Shiny app.
{{embed_app("100%", "500px", "animated")}}
This approach might lead to flickering in certain browsers, as the entire plot is re-rendered for each frame of the animation. For smoother animations, consider using libraries specifically designed for interactive visualizations, such as Plotly or Bokeh, which integrate more seamlessly with web applications.
This approach might lead to flickering in certain browsers, as the entire plot is re-rendered for each frame of the animation. For smoother animations it is recommended to instead use plotly (see [here](https://physicsapps.github.io/teaching/plotly-template.html) for the corresponding template), which integrate more seamlessly with web applications.
71 changes: 71 additions & 0 deletions docs/apps/TemplatePlotly/animated/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import numpy as np
import plotly.graph_objects as go
from shiny import App, Inputs, Outputs, Session, render, ui


app_ui = ui.page_sidebar(
ui.sidebar(
ui.input_slider('amplitude', 'Amplitude', min=0.1, max=2, value=1, step=0.1),
ui.input_dark_mode(id="dark_mode")
),
ui.output_ui("plot", height='100%')
)

def server(input: Inputs, output: Outputs, session: Session):
x = np.linspace(0, 2 * np.pi, 100)

@render.ui
def plot():
# Set template based on dark mode
template = "plotly_dark" if input.dark_mode() == "dark" else "plotly_white"

amp = input.amplitude()
num_frames = 100

fig = go.Figure(
data=[go.Scatter(x=x, y=amp * np.sin(x))],
frames=[
go.Frame(data=[go.Scatter(y=amp * np.sin(x + i / num_frames * 2 * np.pi))])
for i in range(num_frames)
]
)

fig.update_layout(
template=template,
margin=dict(l=20, r=20, t=20, b=20),
showlegend=False
)

# Generate Plotly HTML without full document wrapper
plot_html = fig.to_html(
auto_play=False, # Disable animation here, because we will control it via JavaScript injection below
include_plotlyjs=True,#"cdn",
full_html=False,
div_id="animated_plot"
)

# Inject JavaScript to force infinite looping
loop_script = """
<script>
(function () {
function startAnimation() {
const gd = document.getElementById("animated_plot");
if (!gd || gd.__loopStarted) return;
gd.__loopStarted = true;

function loop() {
Plotly.animate(gd, null, {
frame: { duration: 10, redraw: false },
transition: { duration: 0 }
}).then(loop);
}

loop();
}
startAnimation();
})();
</script>
"""
return ui.HTML(plot_html + loop_script)

app = App(app_ui, server)
45 changes: 9 additions & 36 deletions docs/apps/TemplatePlotly/app.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,45 +7,18 @@ tags:
- Templates
date:
created: 2025-07-01
updated: 2025-11-17
updated: 2025-12-17
hide:
- toc
---

# Plotly Template
Quick example for a simple plotly app.
Plotly is a powerful graphing library that makes interactive, publication-quality graphs online. It is well-suited for both static and animated plots, making it a great choice for web applications.
<!-- more -->

{{embed_app("100%", "550px")}}

```python title="apps/TemplatePlotly/app.py" linenums="1"
import plotly.express as px
from palmerpenguins import load_penguins
from shiny.express import input, ui
from shinywidgets import render_widget

penguins = load_penguins()

ui.input_slider("n", "Number of bins", 1, 100, 20)
ui.input_dark_mode(id="dark_mode")

@render_widget
def plot():
if input.dark_mode() == "dark":
template = "plotly_dark"
else:
template = "plotly_white"

scatterplot = px.histogram(
data_frame=penguins,
x="body_mass_g",
nbins=input.n(),
).update_layout(
template=template,
title={"text": "Penguin Mass", "x": 0.5},
yaxis_title="Count",
xaxis_title="Body Mass (g)",
)

return scatterplot
```
## Simplest plotly plot
The following example demonstrates how to create a simple static plot using Plotly within a Shiny app
{{embed_app("100%", "550px", "static")}}
## Animations using plotly
Plotly makes it easy to create animated plots with minimal setup. The following example demonstrates how to create an animated plot using Plotly within a Shiny app.
{{embed_app("100%", "550px", "animated")}}
Note that this approach requires animations that loop smoothly. The entire frame stack must be preloaded when the plot is first rendered, which may lead to longer initial load times for complex animations. Additionally, this precludes a true "live" animation that updates based on real-time or on-the-fly generated data.
File renamed without changes.
3 changes: 3 additions & 0 deletions docs/apps/TemplatePlotly/static/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
numpy
palmerpenguins
plotly
2 changes: 1 addition & 1 deletion docs/contributing.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ Quick example for a simple matplotlib app. Matplotlib is a popular Python librar
<!-- more -->
This is a simple example to showcase different matplotlib apps using Shiny for Python.
## Simplest matplotlib plot
{{embed_app("100%", "500px", "automatic")}}
{{embed_app("100%", "500px", "static")}}
## Animations using matplotlib
While it is in principle possible to create animations using Matplotlib in Shiny for Python, it requires some additional setup compared to static plots. The following example demonstrates how to create an animated plot using Matplotlib within a Shiny app.
{{embed_app("100%", "500px", "animated")}}
Expand Down