block by emeeks 6decab485fd2e02c9f1e

Simple Scatterplot

Full Screen

A very simple scatterplot.

index.html


<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="utf-8" />
<title>Scatterplot</title>
<style>
.node {
  stroke: #fff;
  stroke-width: 1.5px;
}

.link {
  fill: none;
  stroke: #000;
  stroke-width: 1.5px;
  opacity: 0.4;
  marker-end: url(#end-arrow);
}

</style>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.16/d3.min.js" charset="utf-8" type="text/javascript"></script>
<script>

//These attributes could be derived from the data
attributes = ["price","carat","depth","table","x","y","z"];

colors = d3.scale.ordinal().range(["#827abf", "#f62150", "#6f89b6", "#f5e0b7", "#5b1e37", "#b9e3c5"]);

d3.csv("diamonds.csv", small_scatterplots);

d3.select("body").append("svg")
.attr("height", 500)
.attr("width", 500)

function small_scatterplots(data) {

  //d3.csv pulls in data as strings so they need to be formatted as numbers
  data.forEach(function (d) {
    attributes.forEach(function (att) {
      d[att] = parseFloat(d[att])
    })
  })

  //create scales dynamically for each attribute's extent

  xScale = d3.scale.linear();
    xAttExtent = d3.extent(data, function (d) {return d["y"]});
    xScale.domain(xAttExtent).range([5,495]);

  yScale = d3.scale.linear();
    yAttExtent = d3.extent(data, function (d) {return d["carat"]});
    yScale.domain(yAttExtent).range([495,5]);

  d3.select("svg")
  .append("g");

  d3.select("g").append("rect").style("fill", "white").style("stroke", "black").style("stroke-width", 1)
    .attr("height", 500)
    .attr("width", 500);

    //scatterplot points
    d3.select("g").selectAll("circle")
    .data(data)
    .enter()
    .append("circle")
    .attr("r", 2)
    .style("fill", colors(0))
    .attr("cx", function (d) {return xScale(d["y"])})
    .attr("cy", function (d) {return yScale(d["carat"])})

    //label
    d3.select("g").append("text")
    .attr("x", 250)
    .style("text-anchor", "middle")
    .attr("y", 15)
    .text("y - caret");


}

</script>
</body>
</html>