@@ -1839,6 +1839,57 @@ def index():
18391839 )
18401840 )
18411841
1842+ serve()
1843+
1844+ </example>
1845+ <example name="Plotly Selections">
1846+ import plotly.express as px
1847+ from fasthtml.common import *
1848+
1849+ # Add the Plotly library to the headers
1850+ app, rt = fast_app(hdrs=(Script(src="https://cdn.plot.ly/plotly-2.24.1.min.js"),))
1851+
1852+ def create_scatter_plot():
1853+ # Create simple scatter plot with 5 points
1854+ fig = px.scatter(
1855+ x=[1, 2, 3, 4, 5], y=[2, 4, 1, 3, 5], labels={"x": "X Value", "y": "Y Value"}
1856+ )
1857+ return fig.to_json()
1858+
1859+ @rt
1860+ def index():
1861+ return Titled("Interactive Plotly Selection",
1862+ P("Click any point to see its x-value!"),
1863+ # point-info will be updated based on what is clicked
1864+ Div(id="point-info")(P("No point selected yet")),
1865+ # plotly-container will be updated with the plot
1866+ Div(id="plotly-container"),
1867+ # Initialize the plot
1868+ Script(
1869+ f"""
1870+ // All the plot data is given in json form by `create_scatter_plot`
1871+ const plotData = {create_scatter_plot()};
1872+ // Create the plot with that data in location with id `plotly-container`
1873+ Plotly.newPlot('plotly-container', plotData.data, plotData.layout);
1874+
1875+ // Add click event handler
1876+ // Get thing with id `plotly-container`, and on plotly_click event,
1877+ // run the function
1878+ document.getElementById('plotly-container').on('plotly_click', function(data) {{
1879+ // Get the first point clicked
1880+ const point = data.points[0];
1881+ // Make HTMX request when point is clicked with the x-value
1882+ htmx.ajax('GET', `point/${{point.x}}`, {{target: '#point-info'}});
1883+ }});
1884+ """
1885+ ))
1886+
1887+
1888+ @rt("/point/{x_val}")
1889+ def get(x_val: float):
1890+ # Return the x-value of the point clicked to the UI!
1891+ return P(Strong(f"You clicked the point with x-value: {x_val}"))
1892+
18421893serve()
18431894
18441895 </example>
0 commit comments