Skip to content

Commit fb77410

Browse files
authored
Merge pull request #70 from dgwyer/observable-plot
Add Observable Plot chart demo
2 parents 141420b + de8e53d commit fb77410

File tree

5 files changed

+52
-0
lines changed

5 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+
from fasthtml.common import *
2+
import numpy as np
3+
4+
plot_js = """
5+
function createPlot(data) {
6+
const plot = Plot.rectY(data, Plot.binX({y: "count"},{x: d => d.value,fill:"steelblue"})).plot();
7+
const div = document.querySelector("#plot");
8+
div.replaceChildren(plot);
9+
}
10+
11+
// Set up initial load via HTMX
12+
htmx.on('htmx:afterSettle', evt => {
13+
if (evt.detail.target.id === 'data-store') {
14+
// The data is now properly JSON-encoded
15+
const data = JSON.parse(evt.detail.target.textContent);
16+
createPlot(data);
17+
}
18+
});
19+
"""
20+
21+
app, rt = fast_app(
22+
hdrs=(Script(src="https://cdn.jsdelivr.net/npm/d3@7"),
23+
Script(src="https://cdn.jsdelivr.net/npm/@observablehq/[email protected]")))
24+
25+
@rt
26+
def index():
27+
return Div(
28+
H1(A("Observable", href="https://observablehq.com/@observablehq/plot", target="_blank"), " Plot Demo"),
29+
P("The data is randomly generated on the server and is fetched on initial page load."),
30+
P("Try opening the browser developer tools and viewing the Network tab to see the data reponse for each http request."),
31+
# On bytton click it sends a get request to the `get_data` route and puts the response in the `data-store` div
32+
Button("Fetch New Data", get=get_data, hx_target="#data-store", cls='btn btn-primary'),
33+
# Store for the JSON chart data
34+
Div(id="data-store", get=get_data, hx_trigger="load", hidden=True),
35+
# Plot container
36+
Div(id="plot"),
37+
# Include the JavaScript for the plot
38+
Script(plot_js)
39+
)
40+
41+
@rt
42+
def get_data():
43+
# Generate sample data
44+
data = [{"value": float(x)} for x in np.random.randn(100)]
45+
# Return as proper JSON response
46+
return JSONResponse(data)
47+
48+
serve()
263 KB
Loading
10.6 KB
Loading
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
[REQUIRED]
2+
ImageAltText=Demo of Observable Plot charts in FastHTML
3+
ComponentName=Observable Plot Bar Chart
4+
ComponentDescription=How to display an Observable Plot bar chart in FastHTML, by David Gwyer.
File renamed without changes.

0 commit comments

Comments
 (0)