block by denisemauldin 602739d6c96f5d4c6d05f312dc1b90a1

Toggling element visibility in v5 with async/await

Full Screen

This is a multiple line graph demonstrating how to show / hide elements by clicking on other elements. This was written using d3.js v4 and is a follow on to the multiple line graph example here.

This graph is part of the code samples for the update to the book D3 Tips and Tricks to version 4 of d3.js.

forked from d3noob‘s block: Toggling element visibility in v4

forked from denisemauldin‘s block: Toggling element visibility in v4

index.html

<!DOCTYPE html>
<meta charset="utf-8">
<style> /* set the CSS */

.line {
  fill: none;
  stroke: steelblue;
  stroke-width: 2px;
}

.axisSteelBlue text{
  fill: steelblue;
}

.axisRed text{
  fill: red;
}

.legend {
  font: 16px sans-serif;
  font-weight: bold;         
  text-anchor: start;
}

</style>
<body>

<!-- load the d3.js library -->    	
<script src="https://d3js.org/d3.v5.min.js"></script>
<script>

// set the dimensions and margins of the graph
var margin = {top: 20, right: 40, bottom: 60, left: 50},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

// parse the date / time
var parseTime = d3.timeParse("%d-%b-%y");

// set the ranges
var x = d3.scaleTime().range([0, width]);
var y0 = d3.scaleLinear().range([height, 0]);
var y1 = d3.scaleLinear().range([height, 0]);

// define the 1st line
var valueline = d3.line()
    .x(function(d) { return x(d.date); })
    .y(function(d) { return y0(d.close); });

// define the 2nd line
var valueline2 = d3.line()
    .x(function(d) { return x(d.date); })
    .y(function(d) { return y1(d.open); });

// append the svg obgect to the body of the page
// appends a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform",
          "translate(" + margin.left + "," + margin.top + ")");

// get the data
const makeRequest = async () => {
  try {
    // this parse may fail
    const data = await d3.json("data.json");
    return data;
  } catch (err) {
    console.log(err)
    throw Error("Failed to load data")
  }
}

async function drawGraph(data) {
 
  // format the data
  data.forEach(function(d) {
      d.date = parseTime(d.date);
      d.close = +d.close;
      d.open = +d.open;
  });

  // scale the range of the data
  x.domain(d3.extent(data, function(d) { return d.date; }));
  y0.domain([0, d3.max(data, function(d) {return Math.max(d.close);})]);
  y1.domain([0, d3.max(data, function(d) {return Math.max(d.open); })]);

  // add the valueline path.
  svg.append("path")
      .data([data])
      .attr("class", "line")
      .attr("id", "blueLine")
      .attr("d", valueline);

  // add the valueline2 path.
  svg.append("path")
      .data([data])
      .attr("class", "line")
      .attr("id", "redLine")
      .style("stroke", "red")
      .attr("d", valueline2);

  // add the X Axis
  svg.append("g")
      .attr("transform", "translate(0," + height + ")")
      .call(d3.axisBottom(x));

  // add the Y0 Axis
  svg.append("g")
      .attr("class", "axisSteelBlue")
      .call(d3.axisLeft(y0));

  // add the Y1 Axis
  svg.append("g")
      .attr("class", "axisRed")
      .attr("transform", "translate( " + width + ", 0 )")
      .call(d3.axisRight(y1));

  // add the blue line legend
  svg.append("text")
     .attr("x", 0)             
     .attr("y", height + margin.top + 15)    
     .attr("class", "legend")
     .style("fill", "steelblue")         
     .on("click", function(){
       // determine if current line is visible
       var active   = blueLine.active ? false : true,
       newOpacity = active ? 0 : 1;
       // hide or show the elements
       d3.select("#blueLine").style("opacity", newOpacity);
       // update whether or not the elements are active
       blueLine.active = active;
     })
     .text("Blue Line");

  // add the red line legend
  svg.append("text")
     .attr("x", 0)             
     .attr("y", height + margin.top + 35)    
     .attr("class", "legend")
     .style("fill", "red")         
     .on("click", function(){
       // determine if current line is visible
       var active   = redLine.active ? false : true,
       newOpacity = active ? 0 : 1;
       // hide or show the elements
       d3.select("#redLine").style("opacity", newOpacity);
       // update whether or not the elements are active
       redLine.active = active;
     })
     .text("Red Line");

}

makeRequest().then(data => drawGraph(data));
  
</script>
</body>

data.json

[
  {
    "date": "1-May-12",
    "close": 58.13,
    "open": 3.41
  },
  {
    "date": "30-Apr-12",
    "close": 53.98,
    "open": 4.55
  },
  {
    "date": "27-Apr-12",
    "close": 67,
    "open": 6.78
  },
  {
    "date": "26-Apr-12",
    "close": 89.7,
    "open": 7.85
  },
  {
    "date": "25-Apr-12",
    "close": 99,
    "open": 8.92
  },
  {
    "date": "24-Apr-12",
    "close": 130.28,
    "open": 9.92
  },
  {
    "date": "23-Apr-12",
    "close": 166.7,
    "open": 10.13
  },
  {
    "date": "20-Apr-12",
    "close": 234.98,
    "open": 12.23
  },
  {
    "date": "19-Apr-12",
    "close": 345.44,
    "open": 13.45
  },
  {
    "date": "18-Apr-12",
    "close": 443.34,
    "open": 16.04
  },
  {
    "date": "17-Apr-12",
    "close": 543.7,
    "open": 18.03
  },
  {
    "date": "16-Apr-12",
    "close": 580.13,
    "open": 21.02
  },
  {
    "date": "13-Apr-12",
    "close": 605.23,
    "open": 22.34
  },
  {
    "date": "12-Apr-12",
    "close": 622.77,
    "open": 20.15
  },
  {
    "date": "11-Apr-12",
    "close": 626.2,
    "open": 21.26
  },
  {
    "date": "10-Apr-12",
    "close": 628.44,
    "open": 31.04
  },
  {
    "date": "9-Apr-12",
    "close": 636.23,
    "open": 35.04
  },
  {
    "date": "5-Apr-12",
    "close": 633.68,
    "open": 41.02
  },
  {
    "date": "4-Apr-12",
    "close": 624.31,
    "open": 43.05
  },
  {
    "date": "3-Apr-12",
    "close": 629.32,
    "open": 46.03
  },
  {
    "date": "2-Apr-12",
    "close": 618.63,
    "open": 51.03
  },
  {
    "date": "30-Mar-12",
    "close": 599.55,
    "open": 53.42
  },
  {
    "date": "29-Mar-12",
    "close": 609.86,
    "open": 57.82
  },
  {
    "date": "28-Mar-12",
    "close": 617.62,
    "open": 59.01
  },
  {
    "date": "27-Mar-12",
    "close": 614.48,
    "open": 56.03
  },
  {
    "date": "26-Mar-12",
    "close": 606.98,
    "open": 58.01
  }
]