I am rendering a svg line chart using d3. For y axis the maximum value in chart data is 104 and minimum is 0. I have taken height of chart to 500. But the maximum value i.e 104 should be rendered at top height but its rendering at height somewhere near height of 270.
Also how can I get y value of svg path from x position inside svg bounds?
I am using timestamps for x axis values in chart data
My Code:
import * as shape from "d3-shape";
import { scaleLinear } from "d3-scale";
const SIZE = 500
const data2 = [
{ "weight": 0, "date": 1723939200000 },
{ "weight": 0, "date": 1724284800000 },
{ "weight": 0, "date": 1724371200000 },
{ "weight": 60, "date": 1724493742250 },
{ "weight": 0, "date": 1724544000000 },
{ "weight": 104, "date": 1724653305251 },
{ "weight": 0, "date": 1724716800000 },
{ "weight": 0, "date": 1724803200000 },
{ "weight": 0, "date": 1725235200000 }]
const formattedValues = data2.map((rec) => [rec.weight, rec.date] as [number, number]);
const weights = formattedValues.map((value) => value[0]);
const dates = formattedValues.map((value) => value[1]);
const scaleX = scaleLinear().domain([Math.min(...dates), Math.max(...dates)]).range([0, SIZE]);
const minWeight = Math.min(...weights);
const maxWeight = Math.max(...weights);
const scaleY = scaleLinear().domain([maxWeight, minWeight]).range([0, SIZE])
const path = shape.line().x(([, x]) => scaleX(x) as number).y(([y]) => {
return scaleY(y) as number
})
.curve(shape.curveBasis)(formattedValues) as string
export function Home() {
return (
<div className="homeContainer">
<svg
height={SIZE} width={SIZE} fill="yellow" style={{ border: '2px solid blue' }}>
<path
d={path}
stroke="black"
strokeWidth={2}
/>
</svg>
</div>
)
}
export default Home
blue border is svg width and height and this is how chart renders