Skip to content

Instantly share code, notes, and snippets.

@codetricity
Last active September 6, 2018 14:15
Show Gist options
  • Select an option

  • Save codetricity/8283b9a8831cfb972de1ce3847b48812 to your computer and use it in GitHub Desktop.

Select an option

Save codetricity/8283b9a8831cfb972de1ce3847b48812 to your computer and use it in GitHub Desktop.
Part 2 of simple d3 axis tutorial

Simple Axis Tutorial Part 2

Add Margins

  1. create object to hold margin information

    var margin = {top: 100, bottom: 100, right: 100, left: 50};
    
  2. set up variables for width and height of chart

    var width = 800;
    var height = 600;
    
  3. create variables for svg width and height

    var svgWidth = 800 + margin.right + margin.left;
    var svgHeight = 600 + margin.top + margin.bottom;
    
  4. replace numbers in svg viewport with variables

     var svg = d3.select("body").append("svg")
       .attr("width", svgWidth)
       .attr("height", svgHeight);
    
  5. append group and translate viewport position

      var svg = d3.select("body").append("svg")
          .attr("width", svgWidth)
          .attr("height", svgHeight)
          .append("g")
              .attr("transform", "translate(" + margin.right +
                  "," + margin.top + ")");
    
  6. remove translation of y axis

Imgur

  1. use width and height variables for scale

  2. translate x axis to bottom

use height variable

  svg.append("g")
      .call(d3.axisBottom(xScale))
          .attr("transform", "translate(0, " +
              height + ")");

Imgur

Add Styles to x and y axis

  1. select all text elements of x axis

  2. Create class for x and y axis

    svg.append("g") .call(d3.axisBottom(xScale)) .attr("transform", "translate(0, " + height + ")") .selectAll("text") .attr("class", "xAxis");

  3. change font style in css

Imgur

  1. increase vertical spacing of label and tick mark

    .selectAll("text")
        .attr("class", "xAxis")
        .attr("transform", "translate(0, 4)");
    

Imgur

  1. apply style to y axis

Imgur

Add x axis label

  1. rough placement with default font

      svg.append("g")
         .append("text")
             .text("Distance")
             .attr("x", width/2)
             .attr("y", height + 60)
    
  2. set text-anchor

     .attr("text-anchor", "middle")
    
  3. assign style class

chain an attribute to the "g" tag of "class".

     svg.append("g")
         .attr("class", "xTitle")
         .append("text")

In the css file, set the style for the class xTitle.

Imgur

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