Skip to content

Instantly share code, notes, and snippets.

@pborissow
Last active January 21, 2022 20:02
Show Gist options
  • Save pborissow/7031f7facfd525b517396d9aff93b9f7 to your computer and use it in GitHub Desktop.
Save pborissow/7031f7facfd525b517396d9aff93b9f7 to your computer and use it in GitHub Desktop.
D3 Stuff

D3 Notes

Personal notes on how to do basic stuff in D3

D3 Formatting

Simple Bar Graph

Basic example using a 1d array of data

  //Create svg
    var NS = "http://www.w3.org/2000/svg";
    var svg1 = document.createElementNS(NS, "svg");
    svg1.setAttribute("width", "100%");
    svg1.setAttribute("height", "100%");
    innerDiv.appendChild(svg1);


  //Initialize d3
    var width, height, svg;
    width = innerDiv.offsetWidth;
    height = innerDiv.offsetHeight;
    svg = d3.select(svg1);

  //Get data
    var data = [2,2,2,1,1,24,8,6,2,3,5,1,2,1,1,2,3,3,3,4,0,2,7,3,6,2,7,6,5,6,7,5,28,52,28,11,9,7,42,25,8,6,4,5,3,21,25,22,11,39,23,24,25,17,12,19,29,29,86,42,48,45,63,68,72,41,55,12,5,23,24,36,44,60,91,56,64,7,6,7,7,6,6,9,5,7,6,7,4,4];
    var range = d3.extent(data); //min/max values of the data
    var maxVal = range[1];
    var numVals = data.length;


  //Set margins for the chart
    var margin = {top: 20, right: 30, bottom: 30, left: 40};

  //Create function used to compute x offsets
    var x = d3.scaleLinear()
    .domain([0, numVals])
    .range([margin.left, width - margin.right]);

  //Create function used to compute y offsets
    var y = d3.scaleLinear()
    .domain([0, maxVal])
    .range([height - margin.bottom, margin.top]);

  //Add x-axis label
    svg.append("g")
    .attr("class", "tick")
    .attr("transform", "translate(0," + (height - margin.bottom) + ")")
    .call(d3.axisBottom(x));

  //Add y-axis label
    svg.append("g")
    .attr("class", "tick")
    .attr("transform", "translate(" + margin.left + ",0)")
    .call(d3.axisLeft(y));

  //Add bar chart
    svg.insert("g", "*")
    .attr("fill", "steelblue")
    .selectAll("rect")
    .data(data)
    .enter().append("rect")
    .attr("x", function(d,i) {
        return x(i);
    })
    .attr("y", function(d) {
        return y(d);
    })
    .attr("width", function(d,i) {
        return 3;
    })
    .attr("height", function(d) {
        return y.range()[0] - y(d);
    });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment