I’m trying to just get a simple line on a D3 chart without using an array of data (that will be the next step).
The x-axis is years from 2007 to 2023. The y-axis is numbers from 0.00 to 0.50.
I assume the data pairs I’ll need will be x in a time formatted year and y as a number.
But when I put in the code to draw a line from one point to the other on the chart, nothing appears and I get no error message.
<div id="container"></div>
<script type="module">
const width = 1140;
const height = 400;
const marginTop = 20;
const marginRight = 20;
const marginBottom = 50;
const marginLeft = 70;
//x-axis is years
const x = d3.scaleUtc()
.domain([new Date("2007-01-01"), new Date("2023-01-01")])
.range([marginLeft, width - marginRight]);
//y-axis is numbers between 0 and .5
const y = d3.scaleLinear()
.domain([0, .5])
.range([height - marginBottom, marginTop]);
const svg = d3.create("svg")
.attr("width", width)
.attr("height", height);
svg.append("g")
.attr("transform", `translate(0,${height - marginBottom})`)
.call(d3.axisBottom(x)
.ticks(d3.utcYear.every(1))
);
svg.append("text") //label
.attr("class", "x label")
.attr("text-anchor", "end")
.attr("x", width/2)
.attr("y", height - 6)
.text("Year");
svg.append("text") //label
.attr("class", "y label")
.attr("text-anchor", "end")
.attr("x", -height/3)
.attr("y", 6)
.attr("dy", ".75em")
.attr("transform", "rotate(-90)")
.text("Percent");
svg.append("g")
.attr("transform", `translate(${marginLeft},0)`)
.call(d3.axisLeft(y));
const parseTime = d3.utcFormat("%Y");
svg.append("line") // nothing appears
.style("stroke", "black")
.attr("x1", parseTime(new Date("2007"))) // x position of the first end of the line
.attr("y1", 0.50) // y position of the first end of the line
.attr("x2", parseTime(new Date("2008"))) // x position of the second end of the line
.attr("y2", 0.40);
container.append(svg.node());