<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script> <style> * { margin: 0; padding: 0; border: 0; } body { background: #ffd; } </style> </head> <body> <svg width="100%" height="99vh"></svg> <script> var svg = d3.select('svg'); var path = svg.append("path"); path.attr("fill", "none") .attr("stroke", "steelblue") .attr("stroke-linejoin", "round") .attr("stroke-linecap", "round") .attr("stroke-width", 2); var rect = svg.node().getBoundingClientRect(); var r = function() { return 20 + Math.random() * 50; }; function getRandomColor() { var letters = '0123456789ABCDEF'; var color = '#'; for (var i = 0; i < 6; i++) { color += letters[Math.floor(Math.random() * 16)]; } return color; } var update = function(data) { var count = data.length; var dataValues = data.map(function (d) { return d.value; }); var min = Math.min.apply(null, dataValues), max = Math.max.apply(null, dataValues); var dataScale = d3.scaleLinear().domain([min, max]).range([0, 100]); var percentToPixelXScale = d3.scaleLinear().domain([0, 100]).range([0, rect.width]); var percentToPixelYScale = d3.scaleLinear().domain([0, 100]).range([0, rect.height]); var getX = function (d, i) { var v = (i + 1) * (100 / (count + 1)); return percentToPixelXScale(v); }; var getY = function(d, i) { var v = 100 - dataScale(d.value); return percentToPixelYScale(v) }; var getR = function(d, i) { return d.value; }; // elements to update var u = svg.selectAll('circle') .data(data); // on exit remove u.exit().remove(); var line = d3.line() //.data(data) .x(getX) .y(getY) .curve(d3.curveMonotoneX); // apply smoothing to the line // // elements to add // enter = u.enter() // .append('circle') // .attr("cy", getY) // .attr("fill", function (d, i) { // return d.color; // }); //u.enter() path .datum(data) //.transition() //.ease(d3.easeLinear) .attr("d", line) //.duration(10); //.attr("transform", null) //.transition() //.attr("transform", "translate(" + getX(0, -1) + ")"); // enter // .merge(u) // .transition() // .ease(d3.easeLinear) // .attr('r', Math.sqrt(count / 2)) // .attr('cx', getX) // .attr("cy", getY) // .duration(400); } var len = 200; var dataSet = new Array(len).fill().map(() => { return { value: 0, color: '#000000' }; }); update(dataSet); var oldVal = 0; setInterval(function() { dataSet.push({ value: oldVal , color: getRandomColor() }); oldVal += r() - 45; if (dataSet.length > len) { dataSet.shift(); } update(dataSet); }, 100); </script> </body> </html>
133000cookie-checkD3 Line chart example