在JavaScript中,我想使用function-plot绘制一个函数。最后,我想绘制一个复杂的函数,而不仅仅是一行函数。代码如下:
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>
但是当运行这段代码时,唯一的输出是许多NaN,我在这里做错了什么?
发布于 2020-11-13 06:19:04
默认情况下,function-plot使用区间算法,如果您提供了一个函数,则输入将是区间,输出也应该是区间。
对于scope.x是一个间隔的问题,可以通过指定选项graphType: 'polyline'来禁用间隔的使用。
observable notebook中有多个使用来自HTML元素的输入修改函数的示例
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" />
https://stackoverflow.com/questions/61561168
复制相似问题