Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import React, { useRef, useEffect } from "react";
import * as d3 from "d3";
function LineChart({ data }) {
const chartRef = useRef(null);
const width = 640;
const height = 400;
const marginTop = 20;
const marginRight = 20;
const marginBottom = 30;
const marginLeft = 40;
useEffect(() => {
const x = d3.scaleTime()
.domain([new Date("2018-01-01"), new Date("2023-01-01")])
.range([marginLeft, width - marginRight]);
const y = d3.scaleLinear()
.domain([20000, 40000])
.range([height - marginBottom, marginTop]);
const svg = d3.select(chartRef.current)
.attr("width", width)
.attr("height", height);
svg.append("g")
.attr("transform", `translate(0,${height - marginBottom})`)
.call(d3.axisBottom(x).ticks(d3.timeYear.every(1)).tickFormat(d3.timeFormat("%Y")));
svg.append("g")
.attr("transform", `translate(${marginLeft},0)`)
.call(d3.axisLeft(y));
const line = d3.line()
.x(d => x(d.year))
.y(d => y(d.price));
svg.append("path")
.datum(data)
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-width", 2)
.attr("d", line);
}, [data]);
return <svg ref={chartRef} />;
}
export default LineChart;