gpt4 book ai didi

javascript - 如何为 d3 中的实时图表提供实时数据

转载 作者:太空宇宙 更新时间:2023-11-04 02:27:36 25 4
gpt4 key购买 nike

我有来自 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>

最佳答案

关于javascript - 如何为 d3 中的实时图表提供实时数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37085643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com