Skip to content

Instantly share code, notes, and snippets.

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

  • Save codetricity/37af62329f6dbe7dea5504bd8857d03b to your computer and use it in GitHub Desktop.

Select an option

Save codetricity/37af62329f6dbe7dea5504bd8857d03b to your computer and use it in GitHub Desktop.
Scheduled for 9/11/2018

d3 interval loop part 1

d3.interval syntax

callback function, delay in milliseconds

  • example 1 second delay * function(){ code here }, 1000

      d3.interval(function(){
          console.log("tick");
      }, 1000);
    

put code in separate function

d3.interval( update, 1000);

function update(){
    console.log("tick");
}

append svg to HTML body

var svg = d3.select("body").append("svg")
    .attr("width", "800")
    .attr("height", "400");

Create Circle

  • create circle outside of update loop. Put code below the svg definition
  • put center of circle at center of svg viewport
  • attributes are cx, cy, r

Imgur

create array of 5 color names

var colors = ["blue", "green", "yellow", "orange", "red"];

set up index counter

var index = 0;

remove circle in loop

To prevent hundreds of circles from being created in the infinite loop, remove circle at the top of the loop

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

append new circle in svg

copy code from outside of loop

paste inside of update loop

reset index if it exceeds number of colors

// function for main loop
function update(){
    svg.select("circle").remove();

    if (index >= colors.length - 1) {
        index = 0;
    } else {
        index++;
    }

    svg.append("circle")
    .attr("cx", "400")
    .attr("cy", "200")
    .attr("r", "50");

    console.log(index);
}

Change color based on array loop

Confirm that there is only one <circle> element on the screen at a time. Confirm that color changes.

Imgur

Add text element "temperature"

  • repeat process that you used to create the circle
  • add element below the circle
  • text element does not change
  • center text under circle by using text-anchor and assigning to middle

Imgur

add temperature data

var temperatureData = [
    {city: "San Francisco", lowTemp: 46},
    {city: "San Jose", lowTemp: 42},
    {city: "Washington, DC", lowTemp: 29},
    {city: "Portland, Oregon", lowTemp: 36},
    {city: "Orlando, Florida", lowTemp: 49},
    {city: "Seattle, Washington", lowTemp: 37},
    {city: "New York", lowTemp: 27}
];

set up color scale

var colorScale = d3.scaleLinear()
    .domain([27, 49])
    .range(["blue", "red"]);

modify index to use temperatureData

    if (index >= temperatureData.length - 1) {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment