【发布时间】:2014-05-05 21:42:11
【问题描述】:
是的,所以我正在尝试从 JSON 源中绘制一个简单的折线图;但我遇到了一些我无法弄清楚的错误!
我的 d3.json() 请求应该返回:
[{"timestamp":1399325270,"value":-0.0029460209892230222598710528},{"timestamp":1399325271,"value":-0.0029460209892230222598710528},{"timestamp":1399325279,"value":-0.0029460209892230222598710528},....]
这是我的绘图脚本:
var margin = { top: 20, right: 20, bottom: 30, left: 50 },
width = document.getElementById("chartArea").offsetWidth - margin.left - margin.right,
height = document.getElementById("chartArea").offsetHeight - margin.top - margin.bottom;
var parseDate = d3.time.format("%X");
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var line = d3.svg.line()
.x(function (d) { return x(d.timestamp); })
.y(function (d) { return y(d.value); });
var svg = d3.select("#chartArea").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
//var series = [];
d3.json("/cryptic/performance/benchmark/all", function (error, data) {
data.forEach(function (d) {
d.timestamp = parseDate((new Date(d.timestamp*1000)));
d.value = (+d.value) * 100;
//series.push([d.timestamp, d.value]);
});
x.domain(d3.extent(data, function (d) { return d.timestamp; }));
y.domain(d3.extent(data, function (d) { return d.value; }));
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Price ($)");
console.log(data[0])
svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);
});
我收到的错误如下所示:
Error: Problem parsing d="MNaN,451.6363636363636LNaN,451.6363636363636LNaN,451.6363636363636LNaN,451.6363636363636LNaN,451.6363636363636LNaN,451.6363636363636LNa....
取决于数据的大小,但你明白了!
非常感谢任何帮助,因为我已经开始扯头发了。
【问题讨论】:
-
您确认日期解析正确吗?请注意,您不需要
parseDate,因为您已经在构建Date对象。 -
@LarsKotthoff 您好 Lars,我一直在 Chrome 控制台中使用它。我尝试了 parseDate、parseDate.format 等的各种组合......一些组合给了我在 chrome 控制台中测试时我正在寻找的正确解析,但在运行应用程序时却没有。你知道我的情况需要什么吗?
-
new Date(d.timestamp*1000)应该没问题。 -
@LarsKotthoff 谢谢 我会试试看,但是如果我希望 x 轴上的格式为 %X 怎么办? (即 HH:mm:ss)?
-
不解析,格式化轴标签。参见例如this example.
标签: javascript json parsing svg d3.js