Skip to content

Instantly share code, notes, and snippets.

@TylerRockwell
Created October 29, 2015 12:57
Show Gist options
  • Save TylerRockwell/68d31d578a2275f39e8b to your computer and use it in GitHub Desktop.
Save TylerRockwell/68d31d578a2275f39e8b to your computer and use it in GitHub Desktop.
D3 Notes

D3

d3.select("item"); - selects an element on the page. Stores much more than DOM

d3.selectAll("item"); - selects all items of a given element on a page

d3.select(this);

d3.select("svg").select("circle");

var circles = d3.selectAll("circle")

circles.on("click", function(){ alert("Hi")});

var scale = d3.scale.linear()

scale.domain([2000, 2012]);

Default range is 0-1

scale.range([50, 950]);

<!--/graph.html -->

<svg id="graph">
  <g transform="translate(0, 450) rotate(0)">
  </g>
</svg>

<script src="graph.js"></script>
//graph.js

var scale = d3.scale.linear()
  .domain([2000, 2012])
  .range([50, 950]);

var axis = d3.svg.axis()
  .scale(scale)
  .orient("bottom")
  .ticks(13)
  .tickFormat(d3.format("d"));

var g = d3.select("g");

g.call(axis);

//Plot data points on a graph
g.append("circle").attr("cx", scale(2005)).attr("cy", scale(4)).attr("r", 5)

Good D3 has no loops

Part 2

//graph.js

// ...

// Okay, now all of your axes are set up.  Add code to draw points here.
d3.csv("old_discoveries.csv", function(csv_data){
  g.selectAll("circle")
    .data(csv_data)
    .enter().append("circle")
      .attr("cx", function(point) {return x(point.year)})
      .attr("cy", function(point) {return y(point.important_discoveries)})
      .attr("r", 5)
});


d3.select("#update-data").on("click", function(){
  d3.csv("new_discoveries.csv", function(csv_data){
    var join = g.selectAll("circle")
        .data(csv_data)

    join.attr("cx", function(point) {return x(point.year)})
        .attr("cy", function(point) {return y(point.important_discoveries)})

    join.enter().append("circle")
        .attr("cx", function(point) {return x(point.year)})
        .attr("cy", function(point) {return y(point.important_discoveries)})
        .attr("r", 5);

    join.exit().remove()
  });
});

D3 noobs - Reference for learning

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment