User Tools

Site Tools


mcq:d3_w9-12

DATA ANALYTICS REFERENCE DOCUMENT

Document Title:D3.js summary for reference and MCQ prep
Document No.:1555484680
Author(s):Rita Raher, Gerhard van der Linde

D3.js

Week 12 Final MCQ

by Michael Duignan - Monday, 15 April 2019, 1:07 PM

The Week 12 assessment(based on weeks 9 to 12) - Multiple Choice Quiz on D3.js for the Web Application Development module is now available on moodle.

Please read the instructions carefully and make sure you understand them before attempting the MCQ. The quiz is currently open and will close on Thursday, April 25th (at 11:59pm). An important note is that you have only one attempt to take thequiz. In addition, once you move onto the next question you cannot go back to a previous question. Make sure you have answered the question before moving onto the next question.

Note that the quiz includes multiple choice answers and some questions that require you write a few lines of code.

Also worth noting: This quiz has 20 questions
You have 35 minutes to take this quiz once you start
This quiz is worth 20% of the marks for the module
Not all questions carry the same marks - Questions have either 1 mark, 2 marks or 4 marks (depending on difficulty). The assessment is marked out of 40 marks.

If you have any questions before you attempt the MCQ, please post a reply on the discussion forum to this message and I will get back to you.

Best of luck with the assessment, Regards, Mike

Week 9 - Introduction to D3

Part 1 - Introduction to D3.js

https://d3js.org/ 1) 2) Data-Driven Documents

D3.js - Overview

Purpose

D3(Standing for Data-Driven Documents) is a JavaScript library for producing dynamic, interactive data visualizations in web browsers.

Capabilities

  • Principal functions allow for selections, transitions an data-binding.
    • D3 can select elements in the DOM programmatically(can use instead of the verbose DOM API)
    • By declaring a transition, styles can be smoothly interpolated/animated over a certain time.
    • Large datasets(e.g JSON/XML format) can be easily bound to svg objects using simple D3.js functions to generate rich text/graphic charts and diagrams.

Technologies

  • Built on top of common web standards liek HTML, CSS, JavaScript the DOM and SVG
  • Exportable nature of SVG enables graphics created by D3 to be used in print publications.

Origins

  • Initially released in 2011(successor to the earlier Protovis framework) - Now used widely (e.g by the New York Times, OpenStreetMap etc.)
  • Recent version -v4 has big breaks in the API from previous versions

Part 2 - Introduction to SVGs and XML

Scalable Vector Graphics

D3.js - SVG

  • SVG(Scalable Vector Graohics) is an XML format used for drawing
  • SVG also has a DOM - there are elements with parents and children and attributes, and you can respond to the same mouse/touch events
  • CSS styles and selectors can apply to SVG elements

SVGs have the following structure:

  • The

</code>

Demo:

  <svg width="1000" height="500">
    <rect width="50" height="20" fill="red"/>
  </svg>

You can use classes

.myClass {border:2px solid black}

  <svg class="myClass" width="1000" height="500">
    <rect width="500" height="200" fill="red"/>
  </svg>

Use x to move from the left

  <svg class="myClass" width="1000" height="500">
    <rect x="100" width="500" height="200" fill="red"/>
  </svg>

Use y to move from the top

svg_1.html
<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <meta name="Generator" content="EditPlus®">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <title>Document</title>
  <style type="text/css">
	.myClass {border:2px solid black} 
</style>
 </head>
 <body>
  <svg class="myClass" width="700" height="500">
    <rect x="10" y="10" width="500" height="200" fill="red"/>
    <rect x="60" y="180" width="500" height="200" fill="blue"/>
  </svg
 </body>
</html>

Part 3 - Circles in SVGs

.myClass {border:2px solid black}

  <svg width="1000" height="1000" class="myClass">
    <circle r="50" cy="100" cx="200" fill="green" />
  </svg>

Stroke

  <svg width="1000" height="1000" class="myClass">
    <circle r="50" stroke="blue" stroke-width="20" cy="100" cx="200" fill="green" />
  </svg>

Part 4 - Using D3 to create SVGs

Using D3 to create SVGs

  • Include link reference to D3:
<script src="https//d3js.org/d3.v5.min.js"></script>

Using D3.js to create elements

  • Create an SVG container in the HTML page
  • Access the SVG elements using an associated ID
<svg width="1000" height="1000" id="mySVG">
  • The SVG can be targeted using a D3 selector in JavaScript:
var svgConatiner = d3.select("#mySVG");
  • Elements (such as a rectangle) can then be appended to the svg container:
var myRectangle = svgContainer.append("rect");

The appended element can then have attributes set:

myRectangle.attr("x",100 );
myRectangle.attr("y", 100);
myRectangle.attr("height", 50 );
myRectangle.attr("width", 600 );
myRectangle.attr("fill", "orange" );

Part 5 - D3: Select, Append, and Attr with method chaining

<!DOCTYPE html>
<html>
<head>
 <script src="https//d3js.org/d3.v5.min.js"></script>
</head>
<body>
  <svg width="1000" height="1000" id="mySvg">
  </svg>
 
</body>
</html>
 
<script>
var svgContainer = d3.select("#mySvg");
var myRectangle = svgContainer.append("rect");
 
myRectangle.attr("x", 100);
myRectangle.attr("y", 100);
myRectangle.attr("height", 50);
myRectangle.attr("width", 200);
myRectangle.attr("fill", "orange");
</script>

Method chaining

<!DOCTYPE html>
<html>
<head>
 <script src="https//d3js.org/d3.v5.min.js"></script>
</head>
<body>
  <svg width="1000" height="1000" id="mySvg">
  </svg>
 
</body>
</html>
 
<script>
var svgContainer = d3.select("#mySvg");
//method chaining
var myRectangle = svgContainer.append("rect")
   .attr("x", 100)
   .attr("y", 300)
   .attr("height", 15)
   .attr("width", 200)
   .attr("fill", "green");
</script>

<!DOCTYPE html>
<html>
<head>
 <script src="https//d3js.org/d3.v5.min.js"></script>
</head>
<body>
  <svg width="1000" height="1000" id="mySvg">
  </svg>
 
</body>
</html>
 
<script>
var svgContainer = d3.select("#mySvg");
//method chaining
var myRectangle = svgContainer.append("rect")
   .attr("x", 100)
   .attr("y", 300)
   .attr("height", 15)
   .attr("width", 200)
   .attr("fill", "green");
 
var myCircle = svgContainer.append("circle")
   .attr("cx", 100)
   .attr("cy", 300)
   .attr("r", 250)
   .attr("fill", "Blue");
</script>

<!DOCTYPE html>
<html>
<head>
 <script src="https//d3js.org/d3.v5.min.js"></script>
</head>
<body>
  <svg width="1000" height="1000" id="mySvg">
  </svg>
 
</body>
</html>
 
<script>
var svgContainer = d3.select("#mySvg");
//method chaining
var myRectangle = svgContainer.append("rect")
   .attr("x", 100)
   .attr("y", 300)
   .attr("height", 15)
   .attr("width", 200)
   .attr("fill", "green");
 
var myCircle = svgContainer.append("circle")
   .attr("cx", 100)
   .attr("cy", 300)
   .attr("r", 250)
   .attr("fill", "Blue");
   .attr("stroke", "yellow");
   .attr("stroke-width", 20);
</script>

svg_js.html
<!DOCTYPE html>
<html>
<head>
 <script src="https://d3js.org/d3.v5.min.js"></script>
</head>
<body>
  <svg width="800" height="800" id="mySvg">
  </svg>
 
</body>
</html>
 
<script>
var svgContainer = d3.select("#mySvg");
//method chaining
var myRectangle = svgContainer.append("rect")
   .attr("x", 200)
   .attr("y", 450)
   .attr("height", 15)
   .attr("width", 200)
   .attr("fill", "green");
 
var myCircle = svgContainer.append("circle")
   .attr("cx", 180)
   .attr("cy", 300)
   .attr("r", 150)
   .attr("fill", "Blue")
   .attr("stroke", "yellow")
   .attr("stroke-width", 20);
 
//myRectangle.attr("fill", "Black");
</script>

Week 11 - Charts and Labels in D3

Part 1- Baseline correction in D3

  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Document</title>
  6. <script src="https://d3js.org/d3.v5.min.js"></script>
  7. </head>
  8. <body>
  9. <div id="myDiv"></div>
  10.  
  11. <script type="text/javascript">
  12. //d3.csv("temp_data.csv").then(function(data)
  13. // import the data
  14. d3.csv("temp_data.csv").then(function(data) {
  15. console.log(data);
  16. // create the svg container using d3 select, append svg to div above
  17. let svgContainer = d3.select("#myDiv").append("svg")
  18. .attr("width", 800)
  19. .attr("height", 800);
  20. // create a variable and select all rectangles in svg containe as associate with data
  21. let myRectangle = svgContainer.selectAll("rect")
  22. .data(data);
  23. // using d3 enter method to add rectangles
  24. myRectangle.enter()
  25. .append("rect")
  26. .attr("x",function(d, i){
  27. return 50 + (i*21);
  28. })
  29. .attr("y", function(d){
  30. return 300 - (d.temp *10);
  31. })
  32. .attr("width", 20)
  33. .attr("height",function(d){
  34. return d.temp * 10;
  35. })
  36. //.attr("fill", "red");
  37. .attr("fill", function(d){
  38. if(d.temp <=10) {return "blue";}
  39. else if (d.temp<=15){return "green";}
  40. else if (d.temp <=20){return "orange";}
  41. else {return "red";}});
  42. });
  43.  
  44. </script>
  45. </body>
  46. </html>

Part 2 - Adding labels in D3

<!doctype html>
<html lang ="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
   <script src="https://d3js.org/d3.v5.js"></script>
</head>
<body>
<div id="myDiv"></div>
</body>
 
<script type="text/javascript">
 
//d3.csv("temp_data.csv").then(function(data)
// import the data
 d3.csv("temp_data.csv").then(function(data) {
 console.log(data);
 // create the svg container using d3 select, append svg to div above
 let svgContainer = d3.select("#myDiv").append("svg")
    .attr("width", 800)
    .attr("height", 800);
  // create a variable and select all rectangles in svg containe as associate with data
  let myRectangle = svgContainer.selectAll("rect")
     .data(data);
  // using d3 enter method to add rectangles
  myRectangle.enter()
     .append("rect")
         .attr("x",function(d, i){
             return 50 + (i*41);
         })
         .attr("y", function(d){
             return 300 - (d.temp *10);
         })
         .attr("width", 40)
         .attr("height",function(d){
             return d.temp * 10;
         })
         //.attr("fill", "red");
         .attr("fill", function(d){
             if(d.temp <=10) {return "blue";}
             else if (d.temp<=15){return "green";}
             else if (d.temp <=20){return "orange";}
             else {return "red";}
         });
 
    // Add label text for bar chart
    let mylabel = svgContainer.selectAll("text")
       .data(data);
    // using d3 enter method to add rectangles
    mylabel.enter()
       .append("text")
           .attr("x",function(d, i){
               return 70 + (i*41);
           })
           .attr("y", function(d){
               return 320 - (d.temp *10);
           })
        .attr("text-anchor", "middle")
        .attr("font-family", "sans-serif")
        .attr("font-size", "20px")
        .attr("fill", "white")
        .text(function(d){
            return d.temp + " \u00B0";
        });
 
             });
 
 
 
</script>
</html>

Part 3 - Transitions and Styles in D3

Using CSS to add Style

Using CSS to style SVG rectangles on hover

rect:hover{ fill:black;}
<!doctype html>
<html lang ="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
   <script src="https://d3js.org/d3.v5.js"></script>
   <style>
   rect:hover{
       fill:black;
   }
 
   </style>
</head>
<body>
<div id="myDiv"></div>
</body>
 
<script type="text/javascript">
 
//d3.csv("temp_data.csv").then(function(data)
// import the data
 d3.csv("temp_data.csv").then(function(data) {
 console.log(data);
 // create the svg container using d3 select, append svg to div above
 let svgContainer = d3.select("#myDiv").append("svg")
    .attr("width", 800)
    .attr("height", 800);
  // create a variable and select all rectangles in svg containe as associate with data
  let myRectangle = svgContainer.selectAll("rect")
     .data(data);
  // using d3 enter method to add rectangles
  myRectangle.enter()
     .append("rect")
         .attr("x",function(d, i){
             return 50 + (i*41);
         })
         .attr("y", function(d){
             return 300 - (d.temp *10);
         })
         .attr("width", 40)
         .attr("height",function(d){
             return d.temp * 10;
         })
         //.attr("fill", "red");
         .attr("fill", function(d){
             if(d.temp <=10) {return "blue";}
             else if (d.temp<=15){return "green";}
             else if (d.temp <=20){return "orange";}
             else {return "red";}
         });
 
    // Add label text for bar chart
    let mylabel = svgContainer.selectAll("text")
       .data(data);
    // using d3 enter method to add rectangles
    mylabel.enter()
       .append("text")
           .attr("x",function(d, i){
               return 70 + (i*41);
           })
           .attr("y", function(d){
               return 320 - (d.temp *10);
           })
        .attr("text-anchor", "middle")
        .attr("font-family", "sans-serif")
        .attr("font-size", "20px")
        .attr("fill", "white")
        .text(function(d){
            return d.temp + " \u00B0";
        });
 
             });
 
 
 
</script>
</html>

Transitions in D3.js

D3's .transition() method allows for easy transitions from one state to another.

Instead of applying changes instantaneously, transitions smoothly change from one state to a desired target state, over a given duration.

Transitions are created using the following code:

.transition()

Using the .transition() in conjunction with the .duration() method allows us to specify the time taken to change from the starting state to the finishing state.

The default value in 250 milliseconds. To change the default, a value is specified in the parentheses in the method, specifying the transition duration in milliseconds.

Transitions durations are created using the following code:

.transition(500)
<!doctype html>
<html lang ="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
   <script src="https://d3js.org/d3.v5.js"></script>
   <style>
   rect:hover{
       fill:black;
   }
 
   </style>
</head>
<body>
<div id="myDiv"></div>
</body>
 
<script type="text/javascript">
 
//d3.csv("temp_data.csv").then(function(data)
// import the data
 d3.csv("temp_data.csv").then(function(data) {
 console.log(data);
 // create the svg container using d3 select, append svg to div above
 let svgContainer = d3.select("#myDiv").append("svg")
    .attr("width", 800)
    .attr("height", 800);
  // create a variable and select all rectangles in svg containe as associate with data
  let myRectangle = svgContainer.selectAll("rect")
     .data(data);
  // using d3 enter method to add rectangles
  myRectangle.enter()
     .append("rect")
         // start of transition
         .attr("fill", "black")
         .attr("x",function(d, i){
             return 50 + (i*41);
         })
         .attr("y", 300)
         .attr("width", 300)
         .transition()
         .duration(1000)
         // end of transition
         .attr("x",function(d, i){
             return 50 + (i*41);
         })
         .attr("y", function(d){
             return 300 - (d.temp *10);
         })
         .attr("width", 40)
         .attr("height",function(d){
             return d.temp * 10;
         })
         //.attr("fill", "red");
         .attr("fill", function(d){
             if(d.temp <=10) {return "blue";}
             else if (d.temp<=15){return "green";}
             else if (d.temp <=20){return "orange";}
             else {return "red";}
         });
 
    // Add label text for bar chart
    let mylabel = svgContainer.selectAll("text")
       .data(data);
    // using d3 enter method to add rectangles
    mylabel.enter()
       .append("text")
       .attr("x",function(d, i){
           return 70 + (i*41);
       })
       .attr("y", 300)
       .transition()
       .duration(3000)
           .attr("x",function(d, i){
               return 70 + (i*41);
           })
           .attr("y", function(d){
               return 320 - (d.temp *10);
           })
        .attr("text-anchor", "middle")
        .attr("font-family", "sans-serif")
        .attr("font-size", "20px")
        .attr("fill", "white")
        .text(function(d){
            return d.temp + " \u00B0";
        });
 
             });
 
 
 
</script>
</html>

Week 12 - Adding Scales and Axis in D3

Part 1 - Introduction to Scales in D3

In D3, scales are functions that map from an input domain to an output range.

var myScale = d3.scaleLinear();
//define the scale
var myScale = d3.scaleLinear()
    .domain([0,600])
    .range([0,600]);
 
//using the scale
myscale(400);

Part 2 - Creating Scales in D3

sales.csv

sales.csv
month,sales
January,40
February,50
March,130
April,120
May,180
June,200
July,210
August,480
September,180
October,200
November,68
December,210

No scaling so add the scaling code.

    var yScale =d3.scaleLinear()
      .domain([0,480])
      .range([0,300]);

Then apply the scaling in one spot only

  1. myRectangle.enter()
  2. .append("rect")
  3. .attr("x",function(d,i){
  4. return (50+(i*21));
  5. })
  6. .attr("y",function(d){
  7. return 300-(d.sales);
  8. })
  9. .attr("width",20)
  10. .attr("height",function(d){
  11. return yScale(d.sales);
  12. })
  13. .attr("fill","red");
  14.  
  15. });

Then in both spots…

  1. myRectangle.enter()
  2. .append("rect")
  3. .attr("x",function(d,i){
  4. return (50+(i*21));
  5. })
  6. .attr("y",function(d){
  7. return 300-yScale(d.sales);
  8. })
  9. .attr("width",20)
  10. .attr("height",function(d){
  11. return yScale(d.sales);
  12. })
  13. .attr("fill","red");
  14.  
  15. });

Automatic Scaling

Use the d3.max feature to find the biggest number in the list to use in automatic scaling.

filename.py
  1. //convert to numbers for d3.max to work properly in scaling
  2. data.forEach(function(d){
  3. d.sales = Number(d.sales);
  4. })
  5. // create a scale for y
  6. var yScale =d3.scaleLinear()
  7. .domain([0,d3.max(data, function(d){
  8. return d.sales;
  9. })])

In order for this to work however, all the strings need to be converted to numbers first. See the code lines two and three to tae care of this.

Then on line 7 use d3.max() and function(d) to set the max value for scaling taken automatically from the dataset.

Final Full Code

scaled_svg.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>D3 Scaling</title>
  <script src="https://d3js.org/d3.v5.min.js"></script>
</head>
<body>
  <div id="myDiv"></div>
  <script type="text/javascript">
    // import the sales data 
    d3.csv("sales.csv").then(function(data) {
    console.log(data);
    // create a scale for y
    var yScale =d3.scaleLinear()
      .domain([0,480])
      .range([0,300]);
    // create the svg container using d3 select, append svg to div above
    let svgContainer = d3.select("#myDiv").append("svg")
    .attr("width", 1000)
    .attr("height", 1000);
    //ceate a rectangle
    var myRectangle = svgContainer.selectAll("rect")
      .data(data);
    //add attributes to rectangle
    myRectangle.enter()
      .append("rect")
        .attr("x",function(d,i){
          return (50+(i*21));
          })
        .attr("y",function(d){
            return 300-yScale(d.sales);
          })
        .attr("width",20)
        .attr("height",function(d){
            return yScale(d.sales);
          })
        .attr("fill","red");
 
    });
  </script>
</body>
</html>

Part 3 - Creating Axes in D3

This section covers the code to generate the axis on the graph. The code that is used to do this is as follow:

var xAxis = d3.axixTop();
var xAxis = d3.axixBottom();
var yAxis = d3.axixLeft();
var yAxis = d3.axixRight();

Code to define the axis.

var xAxis = d3.axisBotom()
  .scale(myScale);

Now the axix needs to be positioned on the screen. Todo this we need to append the axis to the svg container.

    //append the axix to the svg container referincing the svg group **"g"**
    svg.append("g")
      .call(xAxis)

now that the axix exist we need to add and start drawing it to the screen with call(xAxis)

Position the axix using transformations. The translate values determines how many pixels to move the axis horizontally and vertically, so in example ten pixels from the left and 45 down.

    //append the axix to the svg container referincing the svg group **"g"**
    svg.append("g")
      .attr("transform", "translate(10, 45)")
      .call(xAxis)

Full Axis Code implemented

d3js_axis.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>D3 Scaling</title>
  <script src="https://d3js.org/d3.v5.min.js"></script>
</head>
<body>
  <div id="myDiv"></div>
  <script type="text/javascript">
    // import the sales data 
    d3.csv("sales.csv").then(function(data) {
    console.log(data);
    //convert to numbers for d3.max to work properly in scaling
    data.forEach(function(d){
      d.sales = Number(d.sales);
    })
    // create a scale for y
    var yScale =d3.scaleLinear()
      .domain([0,d3.max(data, function(d){
        return d.sales;
      })])
      .range([300,0]);
    //create y Axis
    var yAxis = d3.axisLeft()
        .scale(yScale)
    // create the svg container using d3 select, append svg to div above
    let svgContainer = d3.select("#myDiv").append("svg")
    .attr("width", 1000)
    .attr("height", 1000);
    //ceate a rectangle
    var myRectangle = svgContainer.selectAll("rect")
      .data(data);
    //add attributes to rectangle
    myRectangle.enter()
      .append("rect")
        .attr("x",function(d,i){
          return (50+(i*21));
          })
        .attr("y",function(d){
            return yScale(d.sales);
          })
        .attr("width",20)
        .attr("height",function(d){
            return 300-yScale(d.sales);
          })
        .attr("fill","red");
    //To ensure that the axis is shown on top we do it here after the bars are drawn
    //We will be appending "svgContainer" declared above on line 28
    svgContainer.append("g")
      .attr("transform", "translate(45,0)")
      .call(yAxis);
    });
  </script>
</body>
</html>

Index

mcq/d3_w9-12.txt · Last modified: 2019/04/20 09:22 by gerhard