Javascript 如何使用d3.js绘制线图?
我是d3.js的新手,正在尝试在同一个图上绘制三条线。我正在读取一个tsv文件,它有四列:时间、x、y和z。这是加速度计数据。我想绘制x,y,z列与时间的关系,但似乎无法得到它。有什么建议吗Javascript 如何使用d3.js绘制线图?,javascript,graph,d3.js,line,tsv,Javascript,Graph,D3.js,Line,Tsv,我是d3.js的新手,正在尝试在同一个图上绘制三条线。我正在读取一个tsv文件,它有四列:时间、x、y和z。这是加速度计数据。我想绘制x,y,z列与时间的关系,但似乎无法得到它。有什么建议吗 function graph(){ // Set the dimensions of the canvas / graph var margin = {top: 30, right: 20, bottom: 30, left: 50}, width = 600 - margin.left
function graph(){
// Set the dimensions of the canvas / graph
var margin = {top: 30, right: 20, bottom: 30, left: 50},
width = 600 - margin.left - margin.right,
height = 270 - margin.top - margin.bottom;
// Set the ranges
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
// Define the axes
var xAxis = d3.svg.axis().scale(x)
.orient("bottom").ticks(5);
var yAxis = d3.svg.axis().scale(y)
.orient("left").ticks(5);
// Define the line
var valueline = d3.svg.line()
.x(function(d) { return x(d.time); })
.y(function(d) { return y(d.x); });
var valueline2 = d3.svg.line()
.x(function(d) { return x(d.time); })
.y(function(d) { return y(d.y); })
var valueline3 = d3.svg.line()
.x(function(d) { return x(d.time); })
.y(function(d) { return y(d.z); });
// Adds the svg canvas
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 + ")");
// Get the data
d3.tsv("data/data2.tsv", function(error, data) {
data.forEach(function(d) {
d.time = +d.time;
d.x = +d.x;
d.y = +d.y;
d.z = +d.z;
});
// Scale the range of the data
x.domain(d3.extent(data, function(d) { return d.time; }));
y.domain([0, d3.max(data, function(d) { return Math.max(d.x, d.y, d.z); })]);
// Add the valueline path.
svg.append("path") // Add the valueline path.
.attr("class", "line")
.attr("d", valueline(data));
svg.append("path") // Add the valueline path.
.attr("class", "line")
.style("stroke", "red")
.attr("d", valueline2(data));
svg.append("path") // Add the valueline path.
.attr("class", "line")
.style("stroke", "green")
.attr("d", valueline3(data));
// Add the X Axis
svg.append("g") // Add the X Axis
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Add the Y Axis
svg.append("g") // Add the Y Axis
.attr("class", "y axis")
.call(yAxis);
});}
您可以将每一行一次添加到画布中,但它不是非常d3或高效。最好以适当的方式组织数据。因此,主要问题是数据的准备方式。在指向数据的Lar使用以下代码块嵌套的示例中:
var series = color.domain().map(function(name) {
return {
name: name,
values: data.map(function(d) {
return {
time: d.time,
score: +d[name]
};
})
};
});
这样做的目的是创建一个由3个对象组成的数组。每个对象都有一个键值对:name和
数组。每个数组中都有另一个对象,其中包含用于打印的时间和分数信息。传递给线生成器的是最后一个对象数组
我创建了一个提琴,它在很大程度上基于Lar's所指出的例子,并且自始至终都有评论。此阶段的技巧是检查元素并使用console.log
祝你好运。你看到了吗?是的,我看到了,但没有评论,所以我遇到了一些麻烦。我使用的代码来自