1
1
import plotly .express as px
2
2
from fasthtml .common import *
3
3
4
- app , rt = fast_app ()
5
-
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
6
7
7
def create_scatter_plot ():
8
8
# Create simple scatter plot with 5 points
@@ -11,37 +11,38 @@ def create_scatter_plot():
11
11
)
12
12
return fig .to_json ()
13
13
14
-
15
- @rt ("/" )
16
- def get ():
17
- return Titled (
18
- "Interactive Plotly Selection" ,
19
- Div (
20
- P ("Click any point to see its x-value!" ),
21
- Div (id = "plotly-container" ),
22
- Div (id = "point-info" )(P ("No point selected yet" )),
23
- Script (src = "https://cdn.plot.ly/plotly-2.24.1.min.js" ),
24
- Script (
25
- f"""
26
- // Initialize the plot
27
- const plotData = { create_scatter_plot ()} ;
28
- Plotly.newPlot('plotly-container', plotData.data, plotData.layout);
29
-
30
- // Add click event handler
31
- document.getElementById('plotly-container').on('plotly_click', function(data) {{
32
- const point = data.points[0];
33
- // Make HTMX request when point is clicked
34
- htmx.ajax('GET', `/point/${{point.x}}`, {{target: '#point-info'}});
35
- }});
36
- """
37
- ),
38
- ),
39
- )
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
+ ))
40
41
41
42
42
43
@rt ("/point/{x_val}" )
43
44
def get (x_val : float ):
44
- return P ( f"You clicked the point with x-value: { x_val } " )
45
-
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 } " ))
46
47
47
48
serve ()
0 commit comments