createEffect(() => {
console.log(props.P);
d3.select(ref()).selectAll("*").remove();
let i = 0.08;
let margin = { top: 30, right: 20, bottom: 30, left: 50 },
width = 400 - margin.left - margin.right,
height = 270 - margin.top - margin.bottom;
let x = d3
.scaleLinear()
.domain([0, 3 * 365])
.range([0, width]);
let y = d3
.scaleLinear()
.domain([P, P * 1.25])
.range([height, 0]);
let xAxis = d3.axisBottom(x);
let yAxis = d3.axisLeft(y);
let y1line = d3
.line<{ x: number; y1: number }>()
.x(function (d) {
return x(d.x);
})
.y(function (d) {
return y(d.y1);
});
let y2line = d3
.line<{ x: number; y2: number }>()
.x(function (d) {
return x(d.x);
})
.y(function (d) {
return y(d.y2);
});
let svg = d3
.select(ref())
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
let data = [];
for (let xVal = 0; xVal <= 3 * 365; xVal++) {
data.push({
x: xVal,
y1: xVal * (i / 365) * P + P,
y2: P * Math.pow(1 + i / 365, xVal),
});
}
let y1Path = svg
.append("path")
.datum(data)
.attr("fill", "none")
.attr("stroke", "blue")
.attr("stroke-width", 1.5)
.attr("d", y1line);
let hoverText = svg.append("text");
let overlay = svg
.append("rect")
.attr("class", "overlay")
.attr("width", width)
.attr("height", height)
.style("fill", "none")
.style("pointer-events", "all");
overlay
.on("mousemove", function (event) {
let x0 = x.invert(d3.pointer(event, this)[0]);
let i = d3.bisectLeft(
data.map((d) => d.x),
x0,
1
);
let d0 = data[i - 1];
let d1 = data[i];
let d = x0 - d0.x > d1.x - x0 ? d1 : d0;
setYValues({ y1: d.y1, y2: d.y2 });
})
.on("mouseout", function () {
hoverText.attr("visibility", "hidden");
});
svg
.append("path")
.datum(data)
.attr("fill", "none")
.attr("stroke", "red")
.attr("stroke-width", 1.5)
.attr("d", y2line);
svg
.append("g")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g").call(yAxis);
}, [props.P]);