-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchart.js
69 lines (59 loc) · 1.68 KB
/
chart.js
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
const dateFormatter = d3.timeFormat("%d %B %Y");
const chartBody = d3.select("#chart_body");
d3.csv("data/weekly_fuel_prices_from_2005_to_20221015.csv").then((data) =>
createChart(data)
);
const createChart = (data) => {
const width = 550;
const height = 320;
data = data.map((d) => ({
date: new Date(d.SURVEY_DATE),
price: +d.HEATING_GAS_OIL,
}));
const dateExtent = d3.extent(data, (d) => d.date);
const maxValue = d3.max(data, (d) => d.price);
const yScale = d3.scaleLinear().domain([0, maxValue]).range([height, 0]);
const xScale = d3.scaleTime().domain(dateExtent).range([0, width]);
const valueLine = d3
.line()
.x((d) => xScale(d.date))
.y((d) => yScale(d.price));
chartBody.append("g").call(d3.axisLeft(yScale));
chartBody
.append("g")
.attr("transform", `translate(0, ${height})`)
.call(d3.axisBottom(xScale));
chartBody
.append("path")
.datum(data)
.attr("d", valueLine)
.attr("class", "line");
const div = d3
.select("body")
.append("div")
.attr("class", "tooltip")
.style("opacity", 0);
chartBody
.selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr("r", 3)
.attr("cx", (d) => xScale(d.date))
.attr("cy", (d) => yScale(d.price))
.style("opacity", 0)
.on("mouseover", (d) => {
div.transition().duration(200).style("opacity", 0.9);
div
.html(
dateFormatter(d.target["__data__"].date) +
"<br/>" +
d.target["__data__"].price
)
.style("left", d.x + "px")
.style("top", d.y + "px");
})
.on("mouseout", (d) => {
div.transition().duration(500).style("opacity", 0);
});
};