Forked from d3js - enter(), update() and exit().
Updates:
- Now works with D3 v4.
- Added separate style sheet.
- Removed dependency on eval().
- Initial rendering, and updates, now handled via a single method.
- Added transition for removed circles.
| license: mit |
Forked from d3js - enter(), update() and exit().
Updates:
| <!doctype html> | |
| <html> | |
| <head> | |
| <link rel="stylesheet" type="text/css" href="style.css"> | |
| <script src="http://d3js.org/d3.v4.js"></script> | |
| </head> | |
| <body> | |
| <script> | |
| // 2 different data arrays | |
| var dataArray = [ | |
| [30,35,45,55,70], | |
| [50,55,45,35,20,25,25,40] | |
| ]; | |
| // globals | |
| var dataIndex=1, // set to 1 initially as the index is always toggled | |
| xBuffer=50, | |
| yBuffer=150, | |
| lineLength=400; | |
| // create global svg element | |
| var svg = d3.select("body").append("svg"); | |
| // initialize svg elements and constant attributes | |
| init(); | |
| // render circles on page load | |
| renderCircles(); | |
| function renderCircles() { | |
| // select data set to use | |
| dataIndex = (dataIndex == 0 ? 1 : 0); | |
| // update text label | |
| d3.select('text') | |
| .text("dataset" + dataIndex); | |
| // data join | |
| var circles = svg.selectAll("circle").data(dataArray[dataIndex]); | |
| // EXIT - remove unneeded circles | |
| circles.exit() | |
| .transition() | |
| .attr("r", 0) | |
| .remove(); | |
| // ENTER - create any new circles needed | |
| circles.enter().append("circle") | |
| // set initial x, y, r value for better transition | |
| .attr("cx",function(d,i){ | |
| var spacing = lineLength/dataArray[dataIndex].length; | |
| return xBuffer+(i*spacing) | |
| }) | |
| .attr("cy",yBuffer) | |
| .attr("r", 0) | |
| .merge(circles) // update x, y, r for all existing, and new circles | |
| .transition() | |
| .duration(500) | |
| .attr("cx",function(d,i){ | |
| var spacing = lineLength/dataArray[dataIndex].length; | |
| return xBuffer+(i*spacing) | |
| }) | |
| .attr("cy",yBuffer) | |
| .attr("r",function(d,i){return d}); | |
| } | |
| // add svg elements, and set const attributes | |
| function init() { | |
| // data set text label | |
| svg.append("text") | |
| .attr("x",xBuffer+(lineLength/2)) | |
| .attr("y",50); | |
| // axis line | |
| svg.append("line") | |
| .attr("x1",xBuffer) | |
| .attr("y1",yBuffer) | |
| .attr("x1",xBuffer+lineLength) | |
| .attr("y2",yBuffer); | |
| } | |
| // button to swap over datasets | |
| d3.select("body").append("button") | |
| .text("change data") | |
| .on("click", renderCircles); | |
| </script> | |
| </body> | |
| </html> |
| svg {width:500px; height:500px} | |
| button {float:left} | |
| line {stroke:#ddd;shape-rendering: crispEdges;} | |
| text {text-anchor:middle;} | |
| circle {fill:orange;stroke:orange;fill-opacity:0.5;} | |
| .axis line {fill:none;stroke:#ddd;shape-rendering: crispEdges;} | |
| .axis path {fill:none;} | |
| .axis text {font-size:0.7em;fill:#555;font-family:sans-serif} |