D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
harrisoncramer
Full window
Github gist
Line Chart w/ Transition
<!DOCTYPE html> <meta charset='utf-8'> <head> <link rel="stylesheet" href="styles.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.12.0/d3.min.js"></script> <title>Updating Linechart</title> </head> <body> <div id="option"> <input name="updateButton" type="button" value="Update" onclick="updateData()"/> </div> </body> <script> // Define width/height, dateParser, x/yScale (just range), x/yAxes var margin = {top: 30, right: 20, bottom: 30, left: 20} width = 600 - margin.left - margin.right height = 400 - margin.top - margin.bottom var parseDate = d3.timeParse("%d-%b-%y") var xScale = d3.scaleTime().range([0,width]) var yScale = d3.scaleLinear().range([height,0]) var xAxis = d3.axisBottom().scale(xScale).ticks(6) var yAxis = d3.axisRight().scale(yScale).ticks(5) // Define the line var lineGen = d3.line() .x(function(d){ return xScale(d.date)}) .y(function(d){ return yScale(d.close)}) // Draw SVG (adding margins) and Group to hold parts (transforming by top and left margin) var svg = d3.select("body").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.bottom + margin.top) .style("background-color", "lightgrey") .attr("transform","translate(0,10)") var g = svg.append("g").attr("transform",`translate(${margin.left},${margin.top})`) //Ingest the data d3.csv("data.csv", function(data){ data.forEach(function(d){ d.date = parseDate(d.date); d.close = +d.close; }) // Add domains to scales xScale.domain(d3.extent(data, function(d){return d.date})) yScale.domain([0, d3.max(data, function(d){return d.close})]) //Call the axes g.append("g").attr("class", "axis").attr("id","xAxis") .attr("transform",`translate(0,${height})`) .call(xAxis) g.append("g").attr("class", "axis").attr("id","yAxis") .call(yAxis) //Draw the line g.append("path") .attr("class","line") .attr("d", lineGen(data)) }) function updateData(){ //Get new data d3.csv("data_alt.csv", function(data){ data.forEach(function(d){ d.date = parseDate(d.date); d.close = +d.close; }) //Change domains, used to create lineGen + axes xScale.domain(d3.extent(data, function(d){ return d.date})) yScale.domain([0,d3.max(data, function(d){return d.close})]) //Change data on line g.select(".line") .transition() .duration(500) .attr("d", lineGen(data)) g.select("#xAxis") .transition() .duration(500) .call(xAxis) g.select("#yAxis") .transition() .duration(500) .call(yAxis) }) } </script>
https://cdnjs.cloudflare.com/ajax/libs/d3/4.12.0/d3.min.js