Last active
June 20, 2023 15:44
-
-
Save crazy4groovy/5c05ad5b6f08e5ff75474bc4a005f729 to your computer and use it in GitHub Desktop.
A simple wrapper for Observable Plot charting lib (ReactJS)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as Plot from "@observablehq/plot"; | |
import PlotFigureChart from "./PlotFigureChart.tsx" | |
export default function MyPlotFigureChart( | |
{ filteredRequests }: { filteredRequests: Readonly<any[]> } | |
) { | |
return ( | |
<PlotFigureChart | |
options={{ | |
inset: 10, | |
y: { | |
label: "Cost ($)", | |
grid: true, | |
}, | |
x: { | |
label: "Date", | |
tickRotate: 15, | |
type: "band", | |
tickFormat: (d: string | Date) => | |
new Date(d).toLocaleDateString("en", { | |
month: "long", | |
day: "numeric", | |
}), | |
// transform: (d: string) => console.log("!", typeof d) || new Date(d), | |
}, | |
color: { | |
legend: true, | |
}, | |
round: true, | |
marks: [ | |
Plot.frame(), | |
/* Plot.rectY(filteredRequests, { | |
// x: (r) => console.log(typeof r.createdAt) || new Date(r.createdAt), | |
x: (r) => new Date(r.createdAt), | |
// x: "createdAt", | |
y: "totalPrice", | |
stroke: "white", | |
fill: "black", | |
tip: true, | |
marginBottom: 50, | |
}), */ | |
Plot.barY( | |
filteredRequests, | |
Plot.groupX<Plot.BarYOptions>( | |
{ y: "sum" }, | |
{ | |
x: (r) => new Date(r.createdAt), | |
// x: "createdAt", | |
y: "totalPrice", | |
marginBottom: 50, | |
fill: "#FFCC00", | |
tip: true, | |
} | |
) | |
), | |
/* Plot.barY(filteredRequests, { | |
// x: (r) => console.log(typeof r.createdAt) || new Date(r.createdAt), | |
x: (r) => new Date(r.createdAt), | |
// x: "createdAt", | |
y: "totalPrice", | |
stroke: "white", | |
strokeOpacity: 0.9, | |
fill: "#FFCC00", | |
fillOpacity: 0.9, | |
tip: true, | |
marginBottom: 50, | |
}), */ | |
Plot.ruleY([0], { stroke: "#AAA" }), | |
], | |
}} | |
/> | |
); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { FC, useEffect, useRef } from "react"; | |
import * as Plot from "@observablehq/plot"; | |
export type Props = { | |
options: Plot.PlotOptions; | |
}; | |
const PlotFigure: FC<Props> = ({ options }) => { | |
const divRef = useRef<HTMLDivElement>(null); | |
useEffect(() => { | |
const element = divRef.current; | |
if (!element) return; | |
element.children[0]?.remove(); | |
const plot = Plot.plot(options); | |
element.appendChild(plot); | |
}, [divRef, options]); | |
return <div ref={divRef} />; | |
}; | |
export default PlotFigure; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment