D3

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

D3 event handler for green button

$btn.on("click", function clickHandler() { // Append a panel div to the page var newPanel = d3.select(".main").append("div"); // Assign class to the panel newPanel.attr("class", "panel panel-warning"); // Append a panel body to the panel var newSubPanel = newPanel.append("div"); // Assign class to the subpanel newSubPanel.attr("class", "panel-body"); // Assign text to the element newSubPanel.text("Hello from the outside"); });

D3 event handler for red button

$transform.on("click", function clickHandler() { // Select all elements of a class d3.selectAll(".panel-body") // Change the text .text("Goodbye for now") // Set its class .attr("class", "goodbye") // Set its class again .attr("class", "panel-body") // Change the font-size .style("font-size", "20px") .style("background", "green"); });

10-Stu_LineChart

// Define SVG area dimensions var svgWidth = 960; var svgHeight = 500; // Define the chart's margins as an object var margin = { top: 60, right: 60, bottom: 60, left: 60 }; // Define dimensions of the chart area var chartWidth = svgWidth - margin.left - margin.right; var chartHeight = svgHeight - margin.top - margin.bottom; // Select body, append SVG area to it, and set its dimensions var svg = d3.select("body") .append("svg") .attr("width", svgWidth) .attr("height", svgHeight); // Append a group area, then set its margins var chartGroup = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); // Configure a parseTime function which will return a new Date object from a string var parseTime = d3.timeParse("%B"); // Load data from miles-walked-this-month.csv d3.csv("miles-walked-this-month.csv", function (error, milesData) { // Throw an error if one occurs if (error) throw error; // Print the milesData console.log(milesData); // Format the date and cast the miles value to a number milesData.forEach(function (data) { data.date = parseTime(data.date); data.miles = +data.miles; }); // Configure a time scale with a range between 0 and the chartWidth // Set the domain for the xTimeScale function // d3.extent returns the an array containing the min and max values for the property specified var xTimeScale = d3.scaleTime() .range([0, chartWidth]) .domain(d3.extent(milesData, data => data.date)) // Configure a linear scale with a range between the chartHeight and 0 // Set the domain for the xLinearScale function var yLinearScale = d3.scaleLinear() .range([chartHeight, 0]) .domain([0, d3.max(milesData, data => data.miles)]); // Create two new functions passing the scales in as arguments // These will be used to create the chart's axes var bottomAxis = d3.axisBottom(xTimeScale); var leftAxis = d3.axisLeft(yLinearScale); // Configure a drawLine function which will use our scales to plot the line's points var drawLine = d3 .line() .x(data => xTimeScale(data.date)) .y(data => yLinearScale(data.miles)); // Append an SVG path and plot its points using the line function chartGroup.append("path") // The drawLine function returns the instructions for creating the line for milesData .attr("d", drawLine(milesData)) .classed("line", true) // Append an SVG group element to the SVG area, create the left axis inside of it chartGroup.append("g") .classed("axis", true) .call(leftAxis); // Append an SVG group element to the SVG area, create the bottom axis inside of it // Translate the bottom axis to the bottom of the page chartGroup.append("g") .classed("axis", true) .attr("transform", "translate(0, " + chartHeight + ")") .call(bottomAxis); });

09-Ins_LineChart

// Define SVG area dimensions var svgWidth = 960; var svgHeight = 500; // Define the chart's margins as an object var margin = { top: 60, right: 60, bottom: 60, left: 60 }; // Define dimensions of the chart area var chartWidth = svgWidth - margin.left - margin.right; var chartHeight = svgHeight - margin.top - margin.bottom; // Select body, append SVG area to it, and set its dimensions var svg = d3.select("body") .append("svg") .attr("width", svgWidth) .attr("height", svgHeight); // Append a group area, then set its margins var chartGroup = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); // Configure a parseTime function which will return a new Date object from a string var parseTime = d3.timeParse("%Y"); // Load data from forcepoints.csv d3.csv("forcepoints.csv", function (error, forceData) { // Throw an error if one occurs if (error) throw error; // Print the forceData console.log(forceData); // Format the date and cast the force value to a number forceData.forEach(function (data) { data.date = parseTime(data.date); data.force = +data.force; }); // Configure a time scale // d3.extent returns the an array containing the min and max values for the property specified var xTimeScale = d3.scaleTime() .domain(d3.extent(forceData, data => data.date)) .range([0, chartWidth]); // Configure a linear scale with a range between the chartHeight and 0 var yLinearScale = d3.scaleLinear() .domain([0, d3.max(forceData, data => data.force)]) .range([chartHeight, 0]); // Create two new functions passing the scales in as arguments // These will be used to create the chart's axes var bottomAxis = d3.axisBottom(xTimeScale); var leftAxis = d3.axisLeft(yLinearScale); // Configure a line function which will plot the x and y coordinates using our scales var drawLine = d3.line() .x(data => xTimeScale(data.date)) .y(data => yLinearScale(data.force)); // Append an SVG path and plot its points using the line function chartGroup.append("path") // The drawLine function returns the instructions for creating the line for forceData .attr("d", drawLine(forceData)) .classed("line", true); // Append an SVG group element to the chartGroup, create the left axis inside of it chartGroup.append("g") .classed("axis", true) .call(leftAxis); // Append an SVG group element to the chartGroup, create the bottom axis inside of it // Translate the bottom axis to the bottom of the page chartGroup.append("g") .classed("axis", true) .attr("transform", `translate(0, ${chartHeight})`) .call(bottomAxis); });

03-Par_BarChart_From_CSV - app,js

// Define SVG area dimensions var svgWidth = 960; var svgHeight = 660; // Define the chart's margins as an object var chartMargin = { top: 30, right: 30, bottom: 30, left: 30 }; // Define dimensions of the chart area var chartWidth = svgWidth - chartMargin.left - chartMargin.right; var chartHeight = svgHeight - chartMargin.top - chartMargin.bottom; // Select body, append SVG area to it, and set the dimensions var svg = d3 .select("body") .append("svg") .attr("height", svgHeight) .attr("width", svgWidth) // Append a group to the SVG area and shift ('translate') it to the right and down to adhere // to the margins set in the "chartMargin" object. var chartGroup = svg.append("g") .attr("transform", `translate(${chartMargin.left}, ${chartMargin.top})`); // Load data from hours-of-tv-watched.csv d3.csv("hours-of-tv-watched.csv", function (error, tvData) { // Log an error if one exists if (error) return console.warn(error); // Print the tvData console.log(tvData); // Cast the hours value to a number for each piece of tvData tvData.forEach(function (data) { data.hours = +data.hours; }); var barSpacing = 10; // desired space between each bar var scaleY = 10; // 10x scale on rect height // @TODO // Create a 'barWidth' variable so that the bar chart spans the entire chartWidth. var barWidth = (chartWidth - (barSpacing * (tvData.length - 1)))/tvData.length; // Create code to build the bar chart using the tvData. chartGroup.selectAll(".bar") .data(tvData) .enter() .append("rect") .classed("bar", true) .attr("width", d => barWidth) .attr("height", d => d.hours * scaleY) .attr("x", (d, i) => i * (barWidth + barSpacing)) .attr("y", d => chartHeight - d.hours * scaleY) });

06-Stu_Complete_Bar_Chart

// Define SVG area dimensions var svgWidth = 960; var svgHeight = 660; // Define the chart's margins as an object var chartMargin = { top: 30, right: 30, bottom: 30, left: 30 }; // Define dimensions of the chart area var chartWidth = svgWidth - chartMargin.left - chartMargin.right; var chartHeight = svgHeight - chartMargin.top - chartMargin.bottom; // Select body, append SVG area to it, and set the dimensions var svg = d3.select("body") .append("svg") .attr("height", svgHeight) .attr("width", svgWidth) // Append a group to the SVG area and shift ('translate') it to the right and to the bottom var chartGroup = svg.append("g") .attr("transform", `translate(${chartMargin.left}, ${chartMargin.top})`); // Load data from hours-of-tv-watched.csv d3.csv("hours-of-tv-watched.csv", function (error, tvData) { if (error) throw error; console.log(tvData); // Cast the hours value to a number for each piece of tvData tvData.forEach(function (d) { d.hours = +d.hours; }); // Configure a band scale for the horizontal axis with a padding of 0.1 (10%) var xBandScale = d3.scaleBand() .domain(tvData.map(d => d.name)) .range([0, chartWidth]) .padding(0.1); // Create a linear scale for the vertical axis. var yLinearScale = d3.scaleLinear() .domain([0, d3.max(tvData, d => d.hours)]) .range([chartHeight, 0]) // Create two new functions passing our scales in as arguments // These will be used to create the chart's axes var bottomAxis = d3.axisBottom(xBandScale); var leftAxis = d3.axisLeft(yLinearScale).ticks(10); // Append two SVG group elements to the chartGroup area, // and create the bottom and left axes inside of them chartGroup.append("g") .call(leftAxis); chartGroup.append("g") .attr("transform", `translate(0, ${chartHeight})`) .call(bottomAxis); // Create one SVG rectangle per piece of tvData // Use the linear and band scales to position each rectangle within the chart chartGroup.selectAll(".bar") .data(tvData) .enter() .append("rect") .attr("class", "bar") .attr("x", d => xBandScale(d.name)) .attr("y", d => yLinearScale(d.hours)) .attr("width", xBandScale.bandwidth()) .attr("height", d => chartHeight - yLinearScale(d.hours)); });

Making_Axes

// Define the dataset var booksIReadThisYear = [12, 8, 7, 16, 2, 4, 11]; var namesArray = [ "Abbott", "Barney", "Costello", "Daisy", "Edward", "Fred", "Georgia" ]; // Store the dimensions of the SVG container var svgWidth = 800; var svgHeight = 600; // Create an object to represent the chart's margins within the SVG container var margin = { top: 50, right: 50, bottom: 50, left: 50 }; var chartWidth = svgWidth - margin.left - margin.right; var chartHeight = svgHeight - margin.top - margin.bottom; // Create and size the SVG container. Then append, size, and position an SVG group inside within margins defined earlier var svg = d3.select("#svg-area") .append("svg") .attr("height", svgHeight) .attr("width", svgWidth); var chartGroup = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); // Create a bandScale which will be used to position the charts bars along the x-axis. Include a padding of 10% of the bar's width. var xBandScale = d3.scaleBand() .domain(namesArray) .range([0, chartWidth]) .padding(0.1); // Create a linearScale which will be used to position the charts bars along the y-axis and set their height in relation to the data var yLinearScale = d3.scaleLinear() .domain([0, 20]) .range([chartHeight, 0]); // Use bottomAxis and leftAxis to create the chart's axes using the passed in scales. var bottomAxis = d3.axisBottom(xBandScale); var leftAxis = d3.axisLeft(yLinearScale); // Append a new SVG group to the bottom of the chart, call the bottomAxis function on the new SVG group to insert an axis chartGroup.append("g") .attr("transform", `translate(${margin.left}, ${chartHeight})`) .call(bottomAxis); // Append a new SVG group to the left (default) of the SVG group, call the leftAxis function inside to create the left-axis chartGroup.append("g") .attr("transform", `translate(${margin.left}, 0)`) .call(leftAxis);

02-Ins_Loading_Data - app.js

// Load data from hours-of-tv-watched.csv d3.csv("./hours-of-tv-watched.csv", function (error, tvData) { if (error) console.error; console.log(tvData); // log a list of names var names = tvData.map(data => data.name) console.log("names", names) // Cast the hours value to a number for each piece of tvData tvData.forEach(function (data) { data.hours = +data.hours; console.log("Name:", data.name); console.log("Hours:", data.hours); }); });

04-Evr_Scales - app.js

// Part 1: Max, Min, Extent var dataArr = [10, 20, 2000]; console.log("min value ", d3.min(dataArr)); console.log("max value ", d3.max(dataArr)); console.log("min and max values ", d3.extent(dataArr)); // Part 2: scaleLinear // Imagine you have test scores with possible scores from 0 to 100, // and you want to graph them in an SVG that is 1000 pixels high. testScores = [50, 90, 95, 75, 85]; // a. hard-coded var yScale = d3.scaleLinear() .domain([0, 100]) .range([0,1000]); console.log(`50 returns ${yScale(50)}`) console.log(`75 returns ${yScale(75)}`) console.log(`100 returns ${yScale(100)}`) // b. max and min var svgHeight = 1000 var yScale = d3.scaleLinear() .domain([0, d3.max(testScores)]) .range([0, svgHeight]) console.log(`50 returns ${yScale(50)}`) console.log(`75 returns ${yScale(75)}`) console.log(`95 returns ${yScale(95)}`) // c. extent var yScale = d3.scaleLinear() .domain(d3.extent(testScores)) .range([0, svgHeight]) console.log(`50 returns ${yScale(50)}`) console.log(`75 returns ${yScale(75)}`) console.log(`95 returns ${yScale(95)}`) // Part 3: scaleBand // Imagine you want to visualize student grade information on a bar chart. svgHeight = 600 svgWidth = 1000 testScores = [90, 85, 75, 90] students = ["Han", "Sarah", "Matt", "Ruchi"] var xScale = d3.scaleBand() .domain(students) .range([0, svgWidth]) console.log(`Han's x-coordinate: ${xScale("Han")}`) console.log(`Sarah's x-coordinate: ${xScale(students[1])}`) console.log(`Matt's x-coordinate: ${xScale("Matt")}`) console.log(`Ruchi's x-coordinate: ${xScale(students[3])}`) console.log(`Each band is ${xScale.bandwidth()} pixels wide.`) // The y values are scaled separately. var yScale = d3.scaleLinear() .domain([0, 100]) .range([0, svgHeight]) console.log(`The height of Han's bar: ${yScale(testScores[0])}`)

05-Ins_Intro_to_Axes - app.js

// data var dataArray = [1, 2, 3]; var dataCategories = ["one", "two", "three"]; // svg container var svgHeight = 400; var svgWidth = 1000; // margins var margin = { top: 50, right: 50, bottom: 50, left: 50 }; // chart area minus margins var chartHeight = svgHeight - margin.top - margin.bottom; var chartWidth = svgWidth - margin.left - margin.right; // create svg container var svg = d3.select("#svg-area").append("svg") .attr("height", svgHeight) .attr("width", svgWidth); // shift everything over by the margins var chartGroup = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); // scale y to chart height var yScale = d3.scaleLinear() .domain([0, d3.max(dataArray)]) .range([chartHeight, 0]); // scale x to chart width var xScale = d3.scaleBand() .domain(dataCategories) .range([0, chartWidth]) .padding(0.05); // create axes var yAxis = d3.axisLeft(yScale); var xAxis = d3.axisBottom(xScale); // set x to the bottom of the chart chartGroup.append("g") .attr("transform", `translate(0, ${chartHeight})`) .call(xAxis); // set y to the y axis // This syntax allows us to call the axis function // and pass in the selector without breaking the chaining chartGroup.append("g") .call(yAxis); /* Note: The above code is equivalent to this: var g = chartGroup.append("g"); yAxis(g); */ // Append Data to chartGroup chartGroup.selectAll(".bar") .data(dataArray) .enter() .append("rect") .classed("bar", true) .attr("x", (d, i) => xScale(dataCategories[i])) .attr("y", d => yScale(d)) .attr("width", xScale.bandwidth()) .attr("height", d => chartHeight - yScale(d));

07-Ins_Line_Generators_Intro

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script> </head> <body> <!-- Part 1 : Path HTML --> <svg width="1000" height="1000"> <!-- <path d="M200,200 600,600 600,800" style="stroke:black; stroke-width:3; fill: none;"></path> --> </svg> <svg width="1000" height="1000" xmlns="http://www.w3.org/2000/svg"> </svg> <script> //Part 2: Generating with D3 and Array of points // var coordinates = [ // [100, 120], // [200, 250], // [300, 160], // [400, 200] // ]; // var lineGenerator = d3.line() // console.log("Drawing commands:", lineGenerator(coordinates)) // var svg = d3.select("svg"); // svg.append("path") // .attr("fill", "none") // .attr("stroke", "blue") // .attr("stroke-width", 5) // .attr("d", lineGenerator(coordinates)) //Part 3: Scaling and using accessor functions. // var dataArray = [ // {x: 5, y: 1}, // {x: 10, y: 5}, // {x: 20, y: 3}, // {x: 25, y: 10} // ]; // var xScale = d3.scaleLinear() // .domain([0, d3.max(dataArray, d => d.x)]) // .range([0, 500]) // var yScale = d3.scaleLinear() // .domain([0, d3.max(dataArray, d => d.y)]) // .range([500, 0]) // var lineGenerator = d3.line() // .x(d => xScale(d.x)) // .y(d => yScale(d.y)); // console.log("Drawing commands:", lineGenerator(dataArray)); // var svg = d3.select("svg"); // svg.append("path") // .attr("fill", "none") // .attr("stroke", "orange") // .attr("stroke-width", 5) // .attr("d", lineGenerator(dataArray)); </script> </body> </html>

Time_Scales - index.html

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Intro To Scales</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script> </head> <body> <script> var precipitation = [ {'year': 2011, 'rainfall': 25}, {'year': 2012, 'rainfall': 30}, {'year': 2013, 'rainfall': 35} ]; var timeExtent = d3.extent(precipitation, d => d.year); //[2011, 2013] var timeScale = d3.scaleTime() .domain(timeExtent) .range([0, 1000]); </script> </body> </html>

Time_Scales - d3scaleband

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Intro To Scales</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.7.3/d3.min.js"></script> </head> <body> </body> </html> <script> //ANOTHER THOUGHT EXPERIMENT // Now imagine that you want to create a bar chart of the first four presidents (and perhaps their age) // Your screen is 1000 pixels wide, and you want to spread out the bars representing each president evenly across it // d3.scaleBand() allows automatic positioning of NON-NUMERICAL data, such as strings // .domain() specifies the array of string data // .range() specifies the extent of the screen real estate, in this case from zero to 1000 pixels in width var presidents = ["Washington", "Adams", "Jefferson", "Madison"]; var myOtherScale = d3.scaleBand().domain(presidents).range([0,1000]); // The first element in the array is positioned at 0 pixels console.log(myOtherScale(presidents[0])) // The second element in the array is positioned at 250 pixels console.log(myOtherScale(presidents[1])) console.log(myOtherScale(presidents[2])) // The last element in the array stretches from 750 pixels to the right edge of the screen console.log(myOtherScale(presidents[3])) // Recall that previously, we manually specified the x position of each element // d3.scaleBand, and other scaling functions, allow automatic positioning // .attr("x", function(data, index) { // return index * 60; // }); </script>

Time_Scales - d3scalelinear

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Intro To Scales</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.7.3/d3.min.js"></script> </head> <body> </body> </html> <script> // A THOUGHT EXPERIMENT // Imagine you have a screen that is 1000 pixels tall // You want to display your test scores, which range from zero to one hundred, visually // Question 1: how many pixels tall would a score of 100 be on the screen? // Answer: 1000px // Question 2: how many pixels tall would a score of 0 be on the screen? // Answer: 0px // Question 3: how many pixels tall would a score of 50 be on the screen? // Answer: 500px // Question 4: 75? // Answer: 750px // ACTUAL CODE OF THE ABOVE // domain() defines the extent of the test scores, or from zero to 100 // range() defines, here, the extent of the screen real estate, from 0 to 1000 pixels tall // d3.scaleLinear() translates a specific test score into height (in pixels) var myScale = d3.scaleLinear().domain([0,100]).range([0,1000]); console.log(myScale(100)); console.log(myScale(0)); console.log(myScale(50)); console.log(myScale(75)); </script>

Time_Scales - d3scaletime1

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Intro To Scales</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.7.3/d3.min.js"></script> </head> <body> </body> </html> <script> var precipitation = [ {'year': 2011, 'rainfall': 25}, {'year': 2012, 'rainfall': 30}, {'year': 2013, 'rainfall': 35} ]; // d3.extent() takes a data set and returns its range // Here, it takes the extent of the years in the precipitation object (2011, 2013) var timeExtent = d3.extent(precipitation, (d)=> d.year); console.log(timeExtent); // d3.scaleTime() scales time var timeScale = d3.scaleTime().domain(timeExtent).range([0,1000]); // console.log(timeScale(2011)); // console.log(timeScale(2012)); // console.log(timeScale(2013)); // year 2011 var testDate = precipitation[1]; console.log(timeScale(testDate.year)); </script>

Time_Scales - d3scaletime2

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Intro To Scales</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.7.3/d3.min.js"></script> </head> <body> </body> </html> <script> var precipitation = [ {'year': 2011, 'rainfall': 25}, {'year': 2012, 'rainfall': 30}, {'year': 2013, 'rainfall': 35} ]; // d3.extent() takes a data set and returns its range // Here, it takes the extent of the years in the precipitation object (2011, 2013) var timeExtent = d3.extent(precipitation, (d)=> d.year); console.log(timeExtent); // d3.scaleTime() scales time var timeScale = d3.scaleTime().domain(timeExtent).range([0,1000]); console.log(timeScale(2011)); console.log(timeScale(2012)); console.log(timeScale(2013)); // year 2011 var testDate = precipitation[0]; console.log(timeScale(testDate.year)); //========================================= var rainMax = d3.max(precipitation, (d)=>d.rainfall); var yLinearScale = d3.scaleLinear().domain([0, rainMax]).range([0,1000]); console.log(rainMax); console.log(yLinearScale(30)); // A line generator plots x and y coordinates for each data point // according to the scaling functions previously defined. var drawLine = d3 .line() .x(function(precipitation) { return xTimeScale(d.year); }) .y(function(precipitation) { return yLinearScale(d.rainfall); }); </script>

Select the div with an id

d3.select("#text2").text();

Use chained searches for nested elements

d3.select(".deeplink").select("a").text();

Show the html for the link div

d3.select(".link").html();

Select the link tag with a tag inside. Note: the 'a' tag is in the object.

d3.select(".link");

Search within the link div

d3.select(".link>a").attr("href");

Change an attribute and use chaining to change the text

d3.select(".link>a").attr("href","https://d3js.org/").text("d3js.org");

Select the div with a class

d3.select(".text1").text();

Modify the text

d3.select("h1").text("Hello World");

This is a d3 representation of the element

d3.select("h1");

Select the text from the element

d3.select('h1').text()

Extra_Responsive_Chart

d3.select(window).on("resize", handleResize); // When the browser loads, loadChart() is called loadChart(); function handleResize() { var svgArea = d3.select("svg"); // If there is already an svg container on the page, remove it and reload the chart if (!svgArea.empty()) { svgArea.remove(); loadChart(); } } function loadChart() { var svgWidth = window.innerWidth; var svgHeight = window.innerHeight; var margin = { top: 30, right: 30, bottom: 30, left: 30 }; var chartWidth = svgWidth - margin.left - margin.right; var chartHeight = svgHeight - margin.top - margin.bottom; var svg = d3.select("body").append('svg') .attr("height", svgHeight) .attr("width", svgWidth); var chartGroup = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); d3.csv("hours-of-tv-watched.csv", function (error, tvData) { if (error) return console.warn(error); tvData.forEach(function (data) { data.hours = +data.hours; }) var labels = tvData.map(d => d.name); // scale x to chart var xScale = d3.scaleBand() .domain(labels) .range([0, chartWidth]); var hours = tvData.map(d => d.hours); // scale y var yScale = d3.scaleLinear() .domain([0, d3.max(hours)]) .range([chartHeight, 0]); var yAxis = d3.axisLeft(yScale); var xAxis = d3.axisBottom(xScale); chartGroup.append("g") .attr("transform", `translate(0, ${chartHeight})`) .call(xAxis); chartGroup.append("g") .call(yAxis); var barWidth = chartWidth / tvData.length; chartGroup.selectAll(".bar") .data(tvData) .enter().append("rect") .attr("class", "bar") .attr("x", (d, i) => xScale(labels[i])) .attr("y", d => yScale(d.hours)) .attr("width", xScale.bandwidth()) .attr("height", d => chartHeight - yScale(d.hours)) }); }

Show combining selectAll with select

d3.selectAll("div").select("a").nodes(); Note: this selects all div tags and then all div tags with 'a' tags inside.

Show selectAll

d3.selectAll("li").nodes();

Show setting a style on all nodes

d3.selectAll("li").style("background-color","darkblue").style("color,"white");

Assign green button to a variable

var $btn = d3.select("#green-button");

Create a new element

var $li = d3.select("ul").append("li"); $li.text("Hi, I'm a new item"); //or in one line d3.select("ul").append("li").text("Hi, I'm a new item");

Assign red button to a variable

var $transform = d3.select("#red-button");

/* 4. Imagine three <li> elements already exists on the page. Create code to update the text of that element while also adding three new elements to match the array below. */

var arr = [1, 1, 2, 3, 5, 8] var ul = d3.select("ul") // YOUR CODE HERE // var selection = ul.selectAll("li") .data(arr) .enter() .append("li") .merge(selection) .text(function (d) { return d })

/* 3. Given the following and a an HTML page with no elements currently in the body, use the enter pattern to render three <li> elements to the page with text matching the integers in the array. */

var arr = [1, 2, 3] var ul = d3.select("body").append("ul") //YOUR CODE HERE// var selection = ul.selectAll("li") // creates virtual selection .data(arr) // binds data .enter() .append("li") // appends li element for each item in array (since there are currently none) .text(function (d) { return d }) // sets the text of each element to match the items in array

/* Bonus - Make the code in number 4 more concise by using the ES6 syntax for arrow functions. Then, modify the code to set the text of each element to "(index in the array): (item from the array) */

var selection = ul.selectAll("li") // creates virtual selection .data(arr) // binds data .enter() .append("li") // appends li element for each item in array (since there are currently none) .merge(selection) .text((d, i) => `${i}: ${d}`) // uses arrow function and template literals to set text

08-Stu_Generators_Intro

var svgWidth = 1000; var svgHeight = 500; // create an SVG element var svg = d3.select("#svg-area") .append("svg") .attr("width", svgWidth) .attr("height", svgHeight) // Load csv data d3.csv("NCHS_life_expectancy_at_birth.csv", function (error, lifeData) { if (error) return console.warn(error); console.log(lifeData); //cast the data from the csv as numbers lifeData.forEach(function (data) { data.year = +data.year data.lifeExpectancy = +data.lifeExpectancy }) //Create a scale for your independent (x) coordinates var xScale = d3.scaleLinear() .domain(d3.extent(lifeData, d => d.year)) .range([0, svgWidth]) //Create a scale for your dependent (y) coordinates var yScale = d3.scaleLinear() .domain([0, d3.max(lifeData, d => d.lifeExpectancy)]) .range([svgHeight, 0]) // create a line generator function and store as a variable // use the scale functions for x and y data var createLine = d3.line() .x(data => xScale(data.year)) .y(data => yScale(data.lifeExpectancy)) // Append a path element to the svg, make sure to set the stroke, stroke-width, and fill attributes. svg.append("path") .attr("stroke", "black") .attr("stroke-width", "1") .attr("fill", "none") .attr("d", createLine(lifeData)) });


संबंधित स्टडी सेट्स

Starting Out With Java - Programming Projects

View Set

Chapter 10: Biodiversity 3- Animals

View Set