Skip to content

Instantly share code, notes, and snippets.

@codetricity
Last active September 17, 2018 12:53
Show Gist options
  • Select an option

  • Save codetricity/5639d0b5b61c211142a43102674f4e86 to your computer and use it in GitHub Desktop.

Select an option

Save codetricity/5639d0b5b61c211142a43102674f4e86 to your computer and use it in GitHub Desktop.
Temperature by Month 5 - scales and axis

Temperature by Month 5 - scales and axis

Imgur

Goal

Create X and Y axis

Learning Objectives

  • JavaScript Date objects

Steps

x axis labels

Use scaleTime to get the names of months for the x axis.

x axis

  1. the domain of the d3.scaleTime() consists of two JavaScript date objects
  2. create JavaScript date objects with new Date()
    1. JavaScript date objects require month, day, year
    2. make the first date object Janunary 1, 2018
    3. make the second date object Dec 1, 2018
  3. the range is 0, WIDTH

You will only use the months value from the dates.

    // using this only to show x axis ticks
    var yLabelScale = d3.scaleTime()
        .domain([new Date("January 1, 2018"), new Date("December 1, 2018")])
        .range([0, WIDTH]);

x position

Since the dates on the spreadsheet do not have month, day, year, we can't use the scale above to set the position of each circle.

We will use integer values of 1 to 12 for the months.

monthPosition = d3.scaleLinear()
    .domain([1,12])
    .range([0, WIDTH]);

yScale

The y scale will plot lowest temperature of each month.

To keep things simple, we are not using d3.min and d3.max to find the minimum and maximum values for the y scale.

var yScale = d3.scaleLinear()
    .domain([75, 17])
    .range([ 0, HEIGHT]);

X and Y Axis

    // %B is the full name of the month
    var xAxis = d3.axisBottom(yLabelScale)
        .tickFormat(d3.timeFormat("%B"));

    var yAxis = d3.axisLeft(yScale);

Append to SVG

  1. append "g" element

  2. use keyword .call() to callthe axis

  3. translate x axis to the bottom of the chart

     svg.append("g")
         .call(yAxis);
    
     svg.append("g")
         .attr("transform", "translate(0, " +  HEIGHT + ")")
         .call(xAxis);
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment