我有来自D3的线图示例..问题是我需要按时间间隔提供来自服务器的实时数据并将其提供给D3以绘制图表。至于我搜索过的,我无法找到那个单一的样本..请帮我解决这个问题..我尝试了一些AJAX编码......我的代码是... ...
<html>
<head>
<script src="../D3/d3.min.js"></script>
<script>
var t = -1;
var n = 40;
var v = 0;
var data = d3.range(n).map(next);
function next() {
return {
time: ++t,
value: v = Math.floor(Math.random() * 20)
};
}
var margin = { top: 10, right: 10, bottom: 20, left: 40 },
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.linear()
.domain([0, n - 1])
.range([0, width]);
var y = d3.scale.linear()
.domain([0, 20])
.range([height, 0]);
var line = d3.svg.line()
.interpolate('basis')
.x(function (d, i) { console.log(d.time); return x(d.time); })
.y(function (d, i) { return y(d.value); });
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom);
var g = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var graph = g.append("svg")
.attr("width", width)
.attr("height", height + margin.top + margin.bottom);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var axis = graph.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
g.append("g")
.attr("class", "y axis")
.call(d3.svg.axis().scale(y).orient("left"));
var path = graph.append("g")
.append("path")
.data([data])
.attr("class", "line")
.attr("d", line);
tick();
function tick() {
// push a new data point onto the back
data.push(next());
// update domain
x.domain([t - n, t]);
// redraw path, shift path left
path
.attr("d", line)
.attr("transform", null)
.transition()
.duration(500)
.ease("linear")
.attr("transform", "translate(" + t - 1 + ")")
.each("end", tick);
// shift axis left
axis
.transition()
.duration(700)
.ease("linear")
.call(d3.svg.axis().scale(x).orient("bottom"));
// pop the old data point off the front
data.shift();
}
function loaddata() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "graph.txt ", true);
xhttp.send();
}
</script>
</head>
<body>
<button type="button" onclick="loaddata()">GET DATA</button>
<div id="demo"></div>
<style>
body {
font-family: Verdana, sans-serif;
font-size: 8pt;
line-height: 12pt;
background: #ffffff;
color: #555555;
}
.axis path, .axis line {
fill: none;
stroke: green;
shape-rendering: crispEdges;
}
.line {
fill: none;
stroke: red;
stroke-width: 1px;
}
</style>
</body>
</html>
答案 0 :(得分:2)