我是d3.js中的一个完整的新手,我正在处理一些代码,但它没有创建路径。有人能帮助我弄清楚我做错了什么吗? jsfiddle的链接:http://jsfiddle.net/p8S7p/154/
var data = [
{
data: [
[
1420815600000,
2
],
[
1420826400000,
2
],
[
1420837200000,
2
],
[
1420848000000,
2
],
],
parameter: "t1"
},
{
data: [
[
1420815600000,
2
],
[
1420826400000,
2
],
[
1420837200000,
2
],
[
1420848000000,
2
],
],
parameter: "t2"
}
];
var margin = {
top: 20,
right: 80,
bottom: 30,
left: 50
},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.linear()
.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()
.interpolate("basis")
.x(function (d) { return x(d[0]); })
.y(function (d) {
return y(d[1]);
});
var svg = d3.select("body").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 cities = [];
for (var i = 0; i < data.length; i++) {
var t = {};
t["name"] = data[i].parameter;
t["values"] = [];
for (var j = 0; j < data[i].data.length; j++) {
var m = {};
m["date"] = data[i].data[j][0];
m["temperature"] = data[i].data[j][1];
t["values"].push(m);
}
cities.push(t);
}
x.domain(d3.extent(data[0].data, function (d) {
return d[0];
}));
y.domain([
d3.min(cities, function (c) {
return d3.min(c.values, function (v) {
return v.temperature;
});
}),
d3.max(cities, function (c) {
return d3.max(c.values, function (v) {
return v.temperature;
});
})]);
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("Temperature (ºF)");
var city = svg.selectAll(".city")
.data(cities)
.enter().append("g")
.attr("class", "city");
city.append("path")
.attr("class", "line")
.attr("d", function (d) {
return line(d.values);
});
它的意思是x轴上的日期。我应该如何将毫秒日期解析为D3时间格式?
答案 0 :(得分:0)
在您的代码中
var line = d3.svg.line()
.interpolate("basis")
.x(function (d) { return x(d[0]); }) //this is incorrect why d[0]
.y(function (d) {
return y(d[1]); //this is incorrect why d[1]
});
应该是
var line = d3.svg.line()
.interpolate("basis")
.x(function (d) { return x(d.date); })
.y(function (d) {
return y(d.temperature);
});
因为这就是你在这里解析数据的方式
var cities = [];
for (var i = 0; i < data.length; i++) {
var t = {};
t["name"] = data[i].parameter;
t["values"] = [];
for (var j = 0; j < data[i].data.length; j++) {
var m = {};
m["date"] = data[i].data[j][0];//storing this in date
m["temperature"] = data[i].data[j][1];//storing it in temperature
t["values"].push(m);
}
cities.push(t);
}
工作代码here
希望这有帮助!