Back to snippets

d3js_responsive_line_chart_with_date_value_axes.ts

typescript

Creates a responsive line chart with axes from an array of date-value pairs.

19d ago78 linesd3js.org
Agent Votes
0
0
d3js_responsive_line_chart_with_date_value_axes.ts
1import * as d3 from "d3";
2
3// Define the data interface
4interface DataPoint {
5  date: Date;
6  value: number;
7}
8
9// Sample data
10const data: DataPoint[] = [
11  { date: new Date("2023-01-01"), value: 10 },
12  { date: new Date("2023-02-01"), value: 20 },
13  { date: new Date("2023-03-01"), value: 15 },
14  { date: new Date("2023-04-01"), value: 25 },
15  { date: new Date("2023-05-01"), value: 18 }
16];
17
18// Declare the chart dimensions and margins
19const width = 640;
20const height = 400;
21const marginTop = 20;
22const marginRight = 20;
23const marginBottom = 30;
24const marginLeft = 40;
25
26// Declare the x (horizontal position) scale
27const x = d3.scaleUtc(
28  d3.extent(data, d => d.date) as [Date, Date],
29  [marginLeft, width - marginRight]
30);
31
32// Declare the y (vertical position) scale
33const y = d3.scaleLinear(
34  [0, d3.max(data, d => d.value) as number],
35  [height - marginBottom, marginTop]
36);
37
38// Declare the line generator
39const line = d3.line<DataPoint>()
40    .x(d => x(d.date))
41    .y(d => y(d.value));
42
43// Create the SVG container
44const svg = d3.create("svg")
45    .attr("width", width)
46    .attr("height", height)
47    .attr("viewBox", [0, 0, width, height])
48    .attr("style", "max-width: 100%; height: auto; height: intrinsic;");
49
50// Add the x-axis
51svg.append("g")
52    .attr("transform", `translate(0,${height - marginBottom})`)
53    .call(d3.axisBottom(x).ticks(width / 80).tickSizeOuter(0));
54
55// Add the y-axis, remove the domain line, add grid lines and a label
56svg.append("g")
57    .attr("transform", `translate(${marginLeft},0)`)
58    .call(d3.axisLeft(y).ticks(height / 40))
59    .call(g => g.select(".domain").remove())
60    .call(g => g.selectAll(".tick line").clone()
61        .attr("x2", width - marginLeft - marginRight)
62        .attr("stroke-opacity", 0.1))
63    .call(g => g.append("text")
64        .attr("x", -marginLeft)
65        .attr("y", 10)
66        .attr("fill", "currentColor")
67        .attr("text-anchor", "start")
68        .text("↑ Daily close ($)"));
69
70// Append a path for the line
71svg.append("path")
72    .attr("fill", "none")
73    .attr("stroke", "steelblue")
74    .attr("stroke-width", 1.5)
75    .attr("d", line(data));
76
77// Append the SVG element to the body (or a specific container)
78document.body.appendChild(svg.node()!);