|
| 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() |
0 commit comments