...我正在将图形从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语句不同,它没有被悬挂:
与函数声明不同,JavaScript中的函数表达式不会被悬挂。在定义函数表达式之前,不能使用它们。 (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
值。