我正在尝试从我的服务器制作简单的实时图表,因为我正在使用 d3 和时间序列。问题是我不能翻译(x(-1000)),因为x()需要一个日期,如何克服它并使翻译工作?这是代码:
var data = [];
var curDate = new Date();
var df = d3.time.format.utc('%Y-%m-%d');
var margin = {top: 6, right: 0, bottom: 6, left: 40},
width = 960 - margin.right,
height = 240 - margin.top - margin.bottom;
var svg = d3.select("body").append("p").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.style("margin-left", -margin.left + "px")
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
function draw() {
var x = d3.time.scale.utc().domain([new Date(data[0].year), new Date(data[data.length-1].year)]).range([0, width]);
var y = d3.scale.linear().domain([0, 5]).rangeRound([0, height]);
var line = d3.svg.line()
.interpolate('basis')
.x(function(d, i) { return x(d.year); })
.y(function(d) { return y(d.books);});
svg.append("defs").append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("width", width)
.attr("height", height);
var path = svg
.append("g")
.attr("clip-path", "url(#clip)")
.append('path')
.data([data])
.attr('class', 'line')
.attr('d', line);
tick(path, svg, line, x);
}
var data = [];
var curDate = new Date();
var df = d3.time.format.utc('%Y-%m-%d');
var margin = {top: 6, right: 0, bottom: 6, left: 40},
width = 960 - margin.right,
height = 240 - margin.top - margin.bottom;
var svg = d3.select("body").append("p").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.style("margin-left", -margin.left + "px")
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
function draw() {
var x = d3.time.scale.utc().domain([new Date(data[0].year), new Date(data[data.length-1].year)]).range([0, width]);
var y = d3.scale.linear().domain([0, 5]).rangeRound([0, height]);
var line = d3.svg.line()
.interpolate('basis')
.x(function(d, i) { return x(d.year); })
.y(function(d) { return y(d.books);});
svg.append("defs").append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("width", width)
.attr("height", height);
var path = svg
.append("g")
.attr("clip-path", "url(#clip)")
.append('path')
.data([data])
.attr('class', 'line')
.attr('d', line);
tick(path, svg, line, x);
}
function tick(path, svg, line, x) {
data.push({year: new Date(data[data.length-1].year.getTime() + 2000), books: 5*Math.random()});
path
.attr('d', line)
.attr('transform', null)
.transition()
.duration(2000)
.ease('linear')
.attr('transform', 'translate(' + x(-3600*24) + ')')
.each('end', function() { tick(path, svg, line, x); });
data.shift();
}
d3.text('server.' + df(new Date()) + '.txt', 'text/plain', function(text) {
var lines = text.split("\n");
for (var i in lines) {
if (lines[i].trim().length == 0) continue;
var lineData = lines[i].split(' ');
data.push({year: new Date(parseInt(lineData[0])), books: parseFloat(lineData[1])});
}
draw();
});