D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
CoreyBurkhart
Full window
Github gist
Nile River Flow Line Graph
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; } .label { text-anchor: end; /* stroke: black; */ font-weight: 500; font-size: .75rem; fill: black; } #x, #y { stroke: darkblue; stroke-dasharray: 5,5; } </style> </head> <body> <script> // Feel free to change or delete any of the code you see in this editor! var width = 960, height = 500, margin = 100; var chart_width = width - margin * 2, chart_height = height - margin * 2; var svg = d3.select("body").append("svg") .attr('id', 'root') .attr("width", 960) .attr("height", 500) var g = svg.append('g') .attr('transform', `translate(${margin}, ${margin})`) var x = d3.scaleBand() .range([0, chart_width]) var y = d3.scaleLinear() .range([chart_height, 0]) var line = d3.line() .curve(d3.curveCardinal) d3.csv('Nile.csv', function(d) { var flow = d3.extent(d, function(d) {return Math.floor(Number(d.Nile))}) y.domain([flow[0] - 50, flow[1] + 50]) x.domain(d.map(function(d) { return d.time })) line.x(function(d, i) {return x(Number(d.time))}) .y(function(d, i) {return y(Number(d.Nile))}) //reduce the amount of ticks for x axis var ticks = d.filter(function(d, i) { if((i + 1) % 10 === 0) return d }) .map(function(d) { return Number.parseInt(d.time) }); //create x and y axis var yAxis = d3.axisLeft(y) var xAxis = d3.axisBottom(x) .tickValues(ticks) //explicitly set tick values //append the axis g.append('g') .call(yAxis) .append("text") .attr("transform", "rotate(-90)") .attr("y", 15) .attr('class', 'label') .text('Flow Rate'); g.append('g') .attr('transform', `translate(0, ${chart_height})`) .call(xAxis) //append the main line for chart var lg = g.append('g') .attr('id', 'line') var path = lg.append('path') .attr('d', line(d)) .attr('fill', 'none') .attr('stroke', 'darkblue') //append hover marker and guide lines var marker = lg.append('circle') .attr('r', 3) .attr('fill', 'darkblue') .style('visibility', 'hidden') var xLine = lg.append('line') .attr('id', 'y') var yLine = lg.append('line') .attr('id', 'y') //position marker and guide lines path.on('mouseover mousemove', function(e){ var position = d3.mouse(document.getElementById('line')) marker.attr('cx', position[0]) .attr('cy', position[1]) .style('visibility', 'visible') xLine.attr('x1', position[0]) .attr('x2', position[0]) .attr('y1', chart_height) .attr('y2', position[1]) yLine.attr('y1', position[1]) .attr('y2', position[1]) .attr('x1', 0) .attr('x2', position[0]) }) }) </script> </body>
https://d3js.org/d3.v4.min.js