JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html>
<head>
<title>Plot</title>
<script src="https://d3js.org/d3.v5.min.js"></script>
</head>
<body>
<div id='plot_area'></div>
</body>
</html>
JavaScript
var margin = {top: 10, right: 40, bottom: 10, left:40};
const svgWidth = 700 - margin.left - margin.right;
const svgHeight = 500 - margin.top - margin.bottom;
function f(dist){
if(Math.abs(dist) < 1e-8){
return 1e8;
} else {
return 1/dist;
}
}
function createData(startValue, endValue, resolution) {
let step = (endValue-startValue) / resolution
let array = [];
for (let i=startValue<1e-5 ? 1e-5 : startValue; i<=endValue; i = i + step) {
let tupel = [];
tupel.push(i);
tupel.push(f(i));
array.push(tupel);
}
return array;
}
var svg = d3.select("#plot_area")
.append("svg")
.attr("width", margin.left + svgWidth + margin.right)
.attr("height", margin.top + svgHeight + margin.bottom)
.append("g")
.attr("transform", `translate(${margin.left}, ${margin.top})`)
// Create x and y scales
var xScale = d3.scaleLinear()
.domain([0, 10])
.range([0, svgWidth]);
var yScale = d3.scaleLinear()
.domain([-5, 5])
.range([svgHeight, 0]);
// Draw x and y scales in plot (with transform group)
const xAxis = svg.append("g")
.attr("transform", `translate(0, ${svgHeight/2})`)
.call(d3.axisBottom(xScale))
const yAxis = svg.append("g")
.call(d3.axisLeft(yScale))
const data = createData(0, 10, 1000)
svg.append("path")
.datum(data)
.attr("id", "curve")
.attr("stroke", "red")
.attr("stroke-width", 2)
.attr("fill", "none")
.attr("d", d3.line().x(d=>xScale(d[0])).y(d=>yScale(d[1])))
zoom = d3.zoom()
.scaleExtent([.5, 20])
.extent([[0, 0], [svgWidth, svgHeight]])
.on("zoom", zoomUpdateChart)
svg.append("rect")
.attr("width", svgWidth)
.attr("height", svgHeight)
.style("fill", "none")
.style("pointer-events", "all")
.call(zoom)
function zoomUpdateChart(){
var newxScale = d3.event.transform.rescaleX(xScale)
// here I do something, but it does not feel good, neither does it really work
d3.event.transform.k = 1/...