chart = {
const width = 1000;
const height = 300;
const margin = {top: 10, right: 30, bottom: 30, left: 30};
const x = d3.scaleUtc()
.domain(d3.extent(data, d => d.Date))
.range([margin.left, width - margin.right]);
const y = d3.scaleLinear()
.domain([0, d3.max(data, d => d.Close)])
.range([height - margin.bottom, margin.top]);
const svg = d3.create("svg")
.attr("width", width)
.attr("height", height)
.attr("style", "max-width: 100%; height: intrinsic; font: 10px sans-serif;")
.style("overflow","visible")
.on("pointerenter pointermove", pointermoved)
.on("pointerleave", pointerleft)
.on("touchstart", event => event.preventDefault());
svg.append("g")
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x))
svg.append("g")
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y))
.call(g => g.select(".domain").remove())
.call(g => g.selectAll(".tick line").clone()
.attr("x2", width - margin.left - margin.right)
.attr("stroke-opacity", 0.1))
.call(g => g.append("text")
.attr("x", -margin.left)
.attr("y", 10)
.attr("fill", "currentColor")
.attr("text-anchor", "start")
.text("Price ($)"));
//append a path for the line
svg.append("path")
.attr("fill", "none")
.attr("stroke", "black")
.attr("stroke-width", 1.5)
.attr("d", d3.line()
.x(d => x(d.Date))
.y(d => y(d.Close))
(data));
// Create the tooltip container.
const tooltip = svg.append("g");
function formatValue(value) {
return value.toLocaleString("en", {
style: "currency",
currency: "USD"
});
}
function formatDate(date) {
return date.toLocaleString("en", {
month: "long",
day: "numeric",
year: "numeric",
timeZone: "UTC"
});
}
// Add the event listeners that show or hide the tooltip.
const bisect = d3.bisector(d => d.Date).center;
function pointermoved(event) {
const i = bisect(data, x.invert(d3.pointer(event)[0]));
tooltip.style("display", null);
tooltip.attr("transform", `translate(${x(data[i].Date)},${y(data[i].Close)})`);
const path = tooltip.selectAll("path")
.data([,])
.join("path")
.attr("fill", "white")
.attr("stroke", "black");
const text = tooltip.selectAll("text")
.data([,])
.join("text")
.call(text => text
.selectAll("tspan")
.data([formatDate(data[i].Date), formatValue(data[i].Close)])
.join("tspan")
.attr("x", 0)
.attr("y", (_, i) => `${i * 1}em`)
.attr("font-weight", (_, i) => i ? null : "bold")
.text(d => d));
size(text, path);
}
function pointerleft() {
tooltip.style("display", "none");
}
// Wraps the text with a callout path of the correct size, as measured in the page.
function size(text, path) {
const {x, y, width: w, height: h} = text.node().getBBox();
text.attr("transform", `translate(${-w / 2},${15 - y})`);
path.attr("d", `M${-w / 2 - 10},5H-5l5,-5l5,5H${w / 2 + 10}v${h + 20}h-${w + 20}z`);
}
return svg.node();
}