September 01, 2022

Agenda & Announcements

  • Questions?
  • No in-person class on Thursday
  • Assignment 3 has been posted

D3

Getting the code

Go to d3js.org and click on the compressed file under Download the latest version here:

Set up your working environment

  1. Create a folder with a “source” folder and move the d3.js file to it
  2. Create an index.html file and source d3.js to it
  3. Create a forecast_barplot.js file with the following data:
var forecasts = [
    { city: "DCA", temperature: 92,  order: 0 },
    { city: "JFK", temperature: 96,  order: 1 },
    { city: "SEA", temperature: 77,  order: 2 },
    { city: "TUS", temperature: 102, order: 3 },
    { city: "SFO", temperature: 65,  order: 4 }
];

Appending elements

// select main div
var mainDiv = d3.select("#mainDiv");

// append svg element and assign node to variable
var svg1 = mainDiv.append("svg").attr("height", 300).attr("width", 300);

// add rectangle to svg1
var rectangle2 = svg1.append("rect");
var rectangle2 = svg1.append("rect");

// set attributes for all svg elements
mainDiv.selectAll("rect").attr("width", 35)
                         .attr("height", 35)
                         .style("fill", "steelblue");

Challenge

Creating a barplot

Based on the forecast data, loop over each element, appending a rect to svg1 setting the following attributes: height mapped to temperature, x mapped to order and y to the height of the canvas minus temperature

forecasts.forEach(function(element) {
     svg1.append("rect")
                   .attr(_______, element.temperature)
                   .attr(_______, _______)
                   .attr(_______, _______ - _______);
});

Data

Joins

// select main div
var mainDiv = d3.select("#mainDiv");

// append svg element and assign node to variable
var svg1 = mainDiv.append("svg");

// data
my_data = [{x: 10, y: 10}, {x: 20, y: 20}, {x: 30, y: 30}]

svg1.selectAll("circle")
  .data(my_data)
  .enter().append("circle")
  .attr("cx", function(d) { return d.x; })
  .attr("cy", function(d) { return d.y; })
  .attr("r", 2.5);

Challenge

UK Driver Fatalities

Using the data in driver_fatalities.js, draw a scatterplot using .data(UkDriverFatalities).enter().append("circle"). ...

Add the two axes.