Plotting the x intercept of an analytical function

问题: I'm new to d3.js and while I plan to learn much more it would be great if I can get some specific help on this problem. I would like to plot a vertical line indicating the...

问题:

I'm new to d3.js and while I plan to learn much more it would be great if I can get some specific help on this problem. I would like to plot a vertical line indicating the x-intercept of an analytical function. It would be a bonus if the x-intercept was not determined analytically so that way the method would work for functions whose x-intercept is 'hard' to solve for.

I have a minimum example of a plot that I'd like to add the vertical line to. I am simply plotting y=x+b where b is a parameter the user can control.

EDIT To clarify, I would like a vertical svg line whose x-coordinate is the same as the x-intercept of the function (in my minimal example below the vertical line would be at the position -b). And I would like this vertical line to update based on user input which updates the function. Something like a solid black vertical line which "slides" as the function changes.

<!DOCTYPE html>

<head>
  <title>xintercept</title>
  <meta charset="utf-8">
  <style>
    path.line {
      stroke: red;
      stroke-width: 2px;
      fill: none;
    }
  </style>
  <script src="https://d3js.org/d3.v4.min.js"></script>
</head>

<body>
  <div class='chart'>
    <form>
      <fieldset>
        <label>b:</label>
        <input id=b type=range min=-10 max=10 step=.1 oninput='draw()' value=2 />
        <output></output>
      </fieldset>
    </form>
    <svg></svg>
  </div>
  <script>
    // Setup chart dimensions and margins
    var margin = {
      top: 20,
      right: 20,
      bottom: 20,
      left: 20
    };
    var width = 500 - margin.left - margin.right;
    var height = 300 - margin.top - margin.bottom;

    // Setup scales - notice no domain, we'll do that on chart render
    var x = d3.scaleLinear().range([0, width]);
    var y = d3.scaleLinear().range([height, 0]);
    x.domain([-10, 10]);
    y.domain([-10, 10]);

    // Setup line generator
    var line = d3.line()
      .x(function(d) {
        return x(d.x);
      })
      .y(function(d) {
        return y(d.y);
      });

    // Setup svg element
    var svg = d3.select('svg')
      .attr('width', width + margin.left + margin.right)
      .attr('height', height + margin.top + margin.bottom)
      .append('g')
      .attr('transform', 'translate(' + margin.left + ', ' + margin.top + ')');


    // Create axes
    svg.append('g')
      .attr('class', 'axis axis--x')
      .attr('transform', 'translate(0,' + height / 2 + ')')
      .call(d3.axisBottom(x));

    svg.append('g')
      .attr('class', 'axis axis--y')
      .attr('transform', 'translate(' + width / 2 + ',0)')
      .call(d3.axisLeft(y));

    // Draw chart
    function draw() {
      var bNode = document.querySelector('#b');
      var b = bNode.value;
      bNode.parentNode.querySelector('output').textContent = b;

      // Construct data from a, b, c
      var data = d3.range(-10, 10, 0.01).map(function(v) {
        return {
          x: v,
          y: 1 * v + 1 * b
        };
      });

      // JOIN
      var paths = svg.selectAll('path.line')
        .data([data]);

      // ENTER
      paths.enter().append('path')
        .attr('class', 'line')
        // ENTER + UPDATE
        .merge(paths)
        .transition()
        .duration(0)
        .attr('d', line);
    }

    // Draw the initial chart - this will also be called every time we update the sliders
    draw();
  </script>
</body>

</html>


回答1:

You can use the scales you created to place the line at the negative position defined by the slider.

Here is your slightly modified snippet. Hope it helps.

<!DOCTYPE html>

<head>
  <title>xintercept</title>
  <meta charset="utf-8">
  <style>
    path.line {
      stroke: red;
      stroke-width: 2px;
      fill: none;
    }
  </style>
  <script src="https://d3js.org/d3.v4.min.js"></script>
</head>

<body>
  <div class='chart'>
    <form>
      <fieldset>
        <label>b:</label>
        <input id=b type=range min=-10 max=10 step=.1 oninput='draw()' value=2 />
        <output></output>
      </fieldset>
    </form>
    <svg></svg>
  </div>
  <script>
    // Setup chart dimensions and margins
    var margin = {
      top: 20,
      right: 20,
      bottom: 20,
      left: 20
    };
    var width = 500 - margin.left - margin.right;
    var height = 300 - margin.top - margin.bottom;

    // Setup scales - notice no domain, we'll do that on chart render
    var x = d3.scaleLinear().range([0, width]);
    var y = d3.scaleLinear().range([height, 0]);
    x.domain([-10, 10]);
    y.domain([-10, 10]);

    // Setup line generator
    var line = d3.line()
      .x(function(d) {
        return x(d.x);
      })
      .y(function(d) {
        return y(d.y);
      });

    // Setup svg element
    var svg = d3.select('svg')
      .attr('width', width + margin.left + margin.right)
      .attr('height', height + margin.top + margin.bottom)
      .append('g')
      .attr('transform', 'translate(' + margin.left + ', ' + margin.top + ')');


    // Create axes
    svg.append('g')
      .attr('class', 'axis axis--x')
      .attr('transform', 'translate(0,' + height / 2 + ')')
      .call(d3.axisBottom(x));

    svg.append('g')
      .attr('class', 'axis axis--y')
      .attr('transform', 'translate(' + width / 2 + ',0)')
      .call(d3.axisLeft(y));
    
    var verticalLine = svg.append('line');

    // Draw chart
    function draw() {
      var bNode = document.querySelector('#b');
      var b = bNode.value;
      bNode.parentNode.querySelector('output').textContent = b;

      // Construct data from a, b, c
      var data = d3.range(-10, 10, 0.01).map(function(v) {
        return {
          x: v,
          y: 1 * v + 1 * b
        };
      });

      // JOIN
      var paths = svg.selectAll('path.line')
        .data([data]);

      // ENTER
      paths.enter().append('path')
        .attr('class', 'line')
        // ENTER + UPDATE
        .merge(paths)
        .transition()
        .duration(0)
        .attr('d', line);

      // mod here
      verticalLine
        .attr('x1', () => x(-b))
        .attr('x2', () => x(-b))
        .attr('y1', 0)
        .attr('y2', height + margin.top + margin.bottom)
        .attr('stroke', 'green');
    
  }

    // Draw the initial chart - this will also be called every time we update the sliders
    draw();
  </script>
</body>

</html>

  • 发表于 2019-03-01 03:02
  • 阅读 ( 216 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除