Skip to content

Commit 5d02386

Browse files
authored
Merge pull request #69 from rian-dolphin/main
Add Plotly point selection example to gallery
2 parents 9a60d70 + f130af5 commit 5d02386

File tree

4 files changed

+52
-0
lines changed

4 files changed

+52
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import plotly.express as px
2+
from fasthtml.common import *
3+
4+
# Add the Plotly library to the headers
5+
app, rt = fast_app(hdrs=(Script(src="https://cdn.plot.ly/plotly-2.24.1.min.js"),))
6+
7+
def create_scatter_plot():
8+
# Create simple scatter plot with 5 points
9+
fig = px.scatter(
10+
x=[1, 2, 3, 4, 5], y=[2, 4, 1, 3, 5], labels={"x": "X Value", "y": "Y Value"}
11+
)
12+
return fig.to_json()
13+
14+
@rt
15+
def index():
16+
return Titled("Interactive Plotly Selection",
17+
P("Click any point to see its x-value!"),
18+
# point-info will be updated based on what is clicked
19+
Div(id="point-info")(P("No point selected yet")),
20+
# plotly-container will be updated with the plot
21+
Div(id="plotly-container"),
22+
# Initialize the plot
23+
Script(
24+
f"""
25+
// All the plot data is given in json form by `create_scatter_plot`
26+
const plotData = {create_scatter_plot()};
27+
// Create the plot with that data in location with id `plotly-container`
28+
Plotly.newPlot('plotly-container', plotData.data, plotData.layout);
29+
30+
// Add click event handler
31+
// Get thing with id `plotly-container`, and on plotly_click event,
32+
// run the function
33+
document.getElementById('plotly-container').on('plotly_click', function(data) {{
34+
// Get the first point clicked
35+
const point = data.points[0];
36+
// Make HTMX request when point is clicked with the x-value
37+
htmx.ajax('GET', `point/${{point.x}}`, {{target: '#point-info'}});
38+
}});
39+
"""
40+
))
41+
42+
43+
@rt("/point/{x_val}")
44+
def get(x_val: float):
45+
# Return the x-value of the point clicked to the UI!
46+
return P(Strong(f"You clicked the point with x-value: {x_val}"))
47+
48+
serve()
767 KB
Loading
66.3 KB
Loading
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
[REQUIRED]
2+
ImageAltText=Interactive Plotly chart demonstrating point selection and dynamic updates using HTMX
3+
ComponentName=Interactive Plotly Selection
4+
ComponentDescription=Example showing how to create interactive Plotly charts that communicate with FastHTML routes when data points are selected, enabling dynamic updates and actions based on user selections

0 commit comments

Comments
 (0)