0

In JavaScript I want to plot a function using function-plot. In the end I want to plot a complex function and not just a one-line function. Here is the code:

var parameters = {
  target: '#myFunction',
  data: [{
    fn: function(scope) {
      return scope.x;
    },
    color: 'red',
    closed: false
  }],
  grid: true,
  yAxis: {
    domain: [0, 24]
  },
  xAxis: {
    domain: [0, 365]
  }
};

function plot() {
  var alpha = 23; // a parameter later taken from a html element and to be used in the function.
  // I need to replace the actual function each time I change parameters later. 
  // This is just a simple example.
  parameters.data[0].fn = function(scope) {
    v = alpha * Math.sin(scope.x / 300);
    console.log(v);
    return v;
  };
  functionPlot(parameters);
}
<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="https://mauriciopoppe.github.io/function-plot/js/function-plot.js"></script>

<body onload="plot();"></body>

but when running this code the only output are many NaN's. What am I doing wrong here?

Mauricio Poppe
  • 4,817
  • 1
  • 22
  • 30
Alex
  • 41,580
  • 88
  • 260
  • 469

1 Answers1

0

function-plot uses interval arithmetic by default and if you provide a function the input will be an interval and the output should be an interval too.

For the problem that you have scope.x is an interval (an object with the shape {lo: number, hi: number}, you can disable the use of intervals by specifying the option graphType: 'polyline'.

There are multiple examples in the observable notebook that modify the function with an input that's taken from an HTML element

const options = {
    target: '#root',
    xAxis: { domain: [0, 3] },
    yAxis: { domain: [0, 5] },
    annotations: [
      { x: 1, text: 'a' },
      { x: 2, text: 'b' }
    ],
    data: [
      {
        fn: 'x * x'
      },
      {
        fn: 'x * x',
        range: [1, 2],
        nSamples: 30,
        closed: true
      }
    ]
  }

functionPlot(options)

var input = document.querySelector('#n')
input.addEventListener('change', () => {
  options.data[1].nSamples = input.value
  functionPlot(options)
})
<script src="https://unpkg.com/function-plot@1.22.2/dist/function-plot.js"></script>

<div>
  <input type="range" id="n" name="n" min="1" max="100">
  <label for="n">Number of divisions</label>
</div>

<div id="root" />
Mauricio Poppe
  • 4,817
  • 1
  • 22
  • 30