在d3中的2个坐标之间画一条直线

dag*_*da1 2 d3.js

我在 d3 中绘制了 x 轴和 y 轴。

var margin = {top: 20, right: 100, bottom: 30, left: 100},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var xScale = d3.scale.linear()
    .domain([0, 15])
    .range([0, width]);

var yScale = d3.scale.linear()
    .domain([0, 38])
    .range([height, 0]);

var xAxis = d3.svg.axis()
    .scale(xScale)
    .orient("bottom")
    .innerTickSize(-height)
    .outerTickSize(0)
    .tickPadding(10);

var yAxis = d3.svg.axis()
    .scale(yScale)
    .orient("left")
    .innerTickSize(-width)
    .outerTickSize(0)
    .tickPadding(10);

var svg = d3.select("body").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 + ")");

  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis);
Run Code Online (Sandbox Code Playgroud)

然后我想在这个网格中的两点之间画一条线。

  svg.append('line')
      .style('stroke', 'black')
      .attr('x1', 5)
      .attr('y1', 5)
      .attr('x2', 20)
      .attr('y2', 20);
Run Code Online (Sandbox Code Playgroud)

这是结果的jsbin

所以在网格坐标 (5, 5) 和 (20, 20) 之间没有绘制线。

如何将线放置在我创建的网格的坐标上?

alt*_*lus 5

您正在使用xScaleyScale设置轴时。除了在内部用于生成刻度和刻度标签之外,这些刻度还将提供在 SVG 坐标(刻度范围)和网格使用的坐标(刻度域)(即数据值)之间轻松转换的方法。

要绘制线条,您还需要将比例应用于数据值:

svg.append('line')
    .style('stroke', 'black')
    .attr('x1', xScale(5))
    .attr('y1', yScale(5))
    .attr('x2', xScale(20))
    .attr('y2', yScale(20));
Run Code Online (Sandbox Code Playgroud)