<html> <head> <script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script> <style> svg rect { fill: gray; } svg text { fill: #000; font: 12px sans-serif; text-anchor: end; } .xaxis,.yaxis{ stroke:#000; stroke-width:1; } .line{ stroke:#f00; stroke-width:1; } </style> </head> <body> <script> var data = [{year:2015,value:10},{year:2016,value:5},{year:2017,value:12},{year:2018,value:15}]; var height = 400 scaleFactor = 20, barwidth = 30, offset = 10; var graph = d3.select("body") .append("svg") .attr("width", (barwidth * data.length)+(offset*(data.length+1))) .attr("height", height+(offset*3)); // set the ranges var x = d3.scaleTime().range([0, (barwidth * data.length)+(offset*(data.length+1))]); var y = d3.scaleLinear().range([height, 0]); var valueline = d3.line() .x(function(d) { return x(d.year); }) .y(function(d) { return y(d.value); }); var yaxis = graph.append("line") .attr("x1",0) .attr("x2",0) .attr("y1",0) .attr("y2",height) .classed("yaxis",true); var yaxis2 = graph.append("line") .attr("x1",(barwidth * data.length)+(offset*(data.length+1))) .attr("x2",(barwidth * data.length)+(offset*(data.length+1))) .attr("y1",0) .attr("y2",height) .classed("yaxis",true); var xaxis = graph.append("line") .attr("x1",0) .attr("x2",(barwidth * data.length)+(offset*(data.length+1))) .attr("y1",height) .attr("y2",height) .classed("xaxis",true); var bar = graph.selectAll("g") .data(data) .enter() .append("g") .attr("transform", function(d, i) { return "translate(" + i * barwidth + ",0)"; }); bar.append("rect").attr("y",function(d){ return height-(d.value * scaleFactor); }) .attr("x",function(d,i){ return offset+(i*offset); }) .attr("height", function(d) { return d.value * scaleFactor; }) .attr("width", barwidth - 1); bar.append("text") .attr("x", function(d,i) { return offset+(i*offset)+(barwidth/2); }) .attr("y", height+(offset*2)) .attr("dx", ".35em") .text(function(d) { return d; }); bar.append("line") .attr("x1", function(d,i) { return offset+(i*offset); }) .attr("x2", function(d,i) { return offset+(i*offset)+(barwidth); }) .attr("y1",function(d){return height-(d*scaleFactor)}) .attr("y2",function(d){return height-(d*scaleFactor)}) .classed("line",true); </script> </body> </html>
We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy. Accept Learn more