gpt4 book ai didi

javascript - 如何用D3拟合多项式曲线?

转载 作者:行者123 更新时间:2023-12-01 03:06:07 35 4
gpt4 key购买 nike

我必须遵循index.html中的D3代码:

<!DOCTYPE html>
<svg width="960" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>

var svg = d3.select("svg"),
margin = {top: 60, right: 20, bottom: 40, left: 50},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var x = d3.scaleLinear()
.rangeRound([0, width]);

var y = d3.scaleLinear()
.rangeRound([height, 0]);

var line = d3.line()
.x(function(d) { return x(d.error); })
.y(function(d) { return y(d.close); });

d3.tsv("data.tsv", function(d) {
d.error = d.error;
d.close = +d.close;
return d;
}, function(error, data) {
if (error) throw error;

x.domain(d3.extent(data, function(d) { return d.error; }));
y.domain(d3.extent(data, function(d) { return d.close; }));

g.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x))
.select(".domain")
.remove();

g.append("g")
.call(d3.axisLeft(y))
.append("text")
.attr("fill", "#000")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", "0.71em")
.attr("text-anchor", "end")
.text("Error (%)");

g.append("path")
.datum(data)
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-linejoin", "round")
.attr("stroke-linecap", "round")
.attr("stroke-width", 1.5)
.attr("d", line);
});

</script>

data.tsv 看起来像这样:

error close
100 93.24
200 -85.35
300 53.89
400 -18.57
500 198.1
600 -8.4
700 98.623
800 9.89
900 118.56
1000 98.71

我想为这些数据点拟合一条曲线。现在这段代码只是用直线连接数据点。它看起来像这样:

enter image description here

我想知道如何拟合多项式曲线。

最佳答案

你必须使用line.curve([curve])。作为参数,您传递的曲线类型也是 d3 的一部分。此链接包含一个很好的示例: https://bl.ocks.org/pstuffa/26363646c478b2028d36e7274cedefa6

API 引用:https://github.com/d3/d3-shape/blob/master/README.md#line_curve

关于javascript - 如何用D3拟合多项式曲线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46171347/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com