gpt4 book ai didi

javascript - D3 线和路径 - 图形线不显示

转载 作者:行者123 更新时间:2023-11-30 11:21:41 24 4
gpt4 key购买 nike

...我正在将图表从 v3 移植到 v4,但我在路径线方面遇到了困难。

这是我认为最重要的部分:

<script src="https://d3js.org/d3.v4.min.js"></script>
pdata = [
{
"date": "2018-01-01",
"marketPrice": 3131
},
{
"date": "2018-01-02",
"marketPrice": 3151
}
];

// loop that transforms "date" to new Date(), marketPrice to numeric
// *** added during edit ***

// format the data
pdata.forEach(function(d) {
d.date = new Date (d.date); // difference between this and Ref(3) is...
// ref(3) calls a time parser rather than instantiate new Date()
d.marketPrice = +d.marketPrice;
//console.log("parsing date into: -- Date: " + d.date + " -- Market Price: " + d.marketPrice);
});

// linear scaling functions - xscale() and yscale()
// *** added during edit ***

// Create scales (added in edit)
var xscale = d3.scaleTime()
.domain([
d3.min(pdata, function (d){return d.date}),
d3.max(pdata, function (d){return d.date})
])
.range([GRAPHLEFT, GRAPHRIGHT]);

var yscale = d3.scaleLinear()
.domain([
d3.min(pdata, function (d){return d.marketPrice}),
d3.max(pdata, function (d){return d.marketPrice})
])
.range([GRAPHBOTTOM,GRAPHTOP]);

// axis functions omitted ...these work predictably

svg.append("path")
.data([pdata])
.attr("stroke", "steelblue")
.attr("stroke-width", 3)
.attr("fill", "none")
.attr("d", lineFunc);

var lineFunc = d3.line()
.x(function (d) {
console.log("Graphing x as: " + xscale(d.date)); // updated during edit
return (xscale(d.date)); // updated during edit ... reveals as NaN
})
.y(function (d) {
console.log("Graphing y as: " + yscale(d.marketPrice)); // updated during edit ... reveals as NaN
return (yscale(d.marketPrice));
});

我无法确认来自 lineFunc() 的回调是否真的被调用了。 (现在根据下面的答案解决)

在我的页面中,出现了坐标轴,但没有出现绘图线。

我正在使用这些引用资料和模型:

(1) - https://github.com/d3/d3-shape/blob/master/README.md#line

(2) - https://bl.ocks.org/pstuffa/26363646c478b2028d36e7274cedefa6

(3) - https://bl.ocks.org/d3noob/402dd382a51a4f6eea487f9a35566de0

最佳答案

尽管 d3.line() 是一个方法(即一个函数),var lineFunc = d3.line().etc... 是一个 函数表达式,并且与函数语句不同,它不会提升:

Function expressions in JavaScript are not hoisted, unlike function declarations. You can't use function expressions before you define them. (MDN source)

因此,将 var lineFunc = d3.line().etc... 移动到顶部,在 .attr("d", lineFunc) 之前路径:

var lineFunc = d3.line()
.x(function (d) {
//etc...

svg.append("path")
.data([pdata])
//etc..
.attr("d", lineFunc);

PS:您仍然需要在线生成器中的刻度。您的路径将附加在 SVG 中,但 x 值将是时间戳,y 值是实际的 marketPrice 值。

关于javascript - D3 线和路径 - 图形线不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49605151/

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