D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
skimlik
Full window
Github gist
Scale test
Built with
blockbuilder.org
<!DOCTYPE html> <head> <meta charset="utf-8"> <script src="https://d3js.org/d3.v4.min.js"></script> <style> body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } </style> </head> <body> <script> // Feel free to change or delete any of the code you see in this editor! var data = [ { date: new Date('Mon Jun 11 2018 16:12:17 GMT+0300'), value: 10 }, { date: new Date('Tue Jun 12 2018 16:12:14 GMT+0300'), value: 15 }, { date: new Date('Wed Jun 13 2018 16:12:12 GMT+0300'), value: 20 }, { date: new Date('Thu Jun 14 2018 16:12:08 GMT+0300'), value: 5 }, { date: new Date('Fri Jun 15 2018 16:11:12 GMT+0300'), value: 18 }, ]; var svg = d3.select("body").append("svg") .attr("width", 960) .attr("height", 500) var start = new Date('Fri Jun 15 2018 16:11:12 GMT+0300'); var end = new Date('Fri Jun 20 2018 16:11:12 GMT+0300'); var scaleX = d3.scaleTime() .range([50, 700]) .domain([start, end]); var most = d3.max(data, function(i) { return i.value; }); var scaleY = d3.scaleLinear().range([150, 50]).domain([0, most]); var chart = svg.append('g').selectAll('.bar').data(data); var dates = scaleX.domain(); var totalDays = Math.ceil((dates[1].valueOf() - dates[0].valueOf()) / 86400000); var width = scaleX.range()[1] - scaleX.range()[0]; var barWidth = width / (totalDays - 1) - 3; svg.append("text") .text("Total days: " + totalDays + ' width: ' + width + ' Bar width: ' + barWidth) .attr("y", 200) .attr("x", 50) .attr("font-size", 36) .attr("font-family", "monospace") // Main chart chart.enter().append('rect') .attr('x', function(d, ix) { return scaleX(d.date);}) .attr('y', function(d) { return scaleY(d.value);}) .attr('width', barWidth) .attr('height', function(d) { return scaleY.range()[0] - scaleY(d.value); }) .style('fill', 'steelblue'); // ********************************************** var startCord = scaleX(scaleX.domain()[0]); var endCord = scaleX(scaleX.domain()[1]); svg.append('line') .attr('x1', startCord) .attr('y1', 40) .attr('x2', endCord) .attr('y2', 40) .style('stroke', 'black') svg.append('circle').attr('r', 5).attr('cx', startCord).attr('cy', 40).style('fill', 'steelblue'); svg.append('circle').attr('r', 5).attr('cx', endCord).attr('cy', 40).style('fill', 'steelblue'); svg.append('circle').attr('r', 5).attr('cx', scaleX.range()[0]).attr('cy', 250).style('fill', 'red'); svg.append('circle').attr('r', 5).attr('cx', scaleX.range()[1]).attr('cy', 250).style('fill', 'red'); data.forEach(d => { svg.append('circle').attr('r', 5).attr('cx', scaleX(d.date)).attr('cy', 30).style('fill', 'violet'); }) </script> </body>
https://d3js.org/d3.v4.min.js