D3.JS Tree Map Loading in CSV

247 Views Asked by At
<!DOCTYPE html>
<meta charset="utf-8">

<!-- load D3js -->
<script src="https://d3js.org/d3.v3.js"></script>

<!-- load D3plus after D3js -->
<script src="https://d3plus.org/js/d3plus.js"></script>

<!-- create container element for visualization -->
<div id="viz"></div>

<script>
  // sample data array
  d3.csv("DataVis.csv", function(data){
    console.log(data);
});
  // instantiate d3plus
  var visualization = d3plus.viz()
    .container("#viz")  // container DIV to hold the visualization
    .data(data)  // data to use with the visualization
    .type("tree_map")   // visualization type
    .id("Name")         // key for which our data is unique on
    .size("Amount Spent")      // sizing of blocks
    .draw()             // finally, draw the visualization!
</script>

I keep getting the error "data is not defined" I attached my csv file here

I keep getting errors on this part and im not sure what to do. I would love any feedback

2

There are 2 best solutions below

2
Nick On

Data load will only be complete within the callback function. so you should only attempt to do something with that data after it's loaded.

d3.csv("DataVis.csv", function(data){
  console.log(data);
  // instantiate d3plus
  var visualization = d3plus.viz()
    .container("#viz")  // container DIV to hold the visualization
    .data(data)  // data to use with the visualization
    .type("tree_map")   // visualization type
    .id("Name")         // key for which our data is unique on
    .size("Amount Spent")      // sizing of blocks
    .draw()             // finally, draw the visualization!
});
0
Coola On

There are two main issues with your code.

  1. The visualization part of the code needs to be in the function block with the data (as pointed out by the other answer)
  2. Your data is not true numbers because you have the numbers for Amount Spent in the format "$8,200,000.00". Javascript does not read that as a number, but rather as a string. That is the reason why you get the error [D3 plus] no data available. To rectify this, you need to do a "type conversion" i.e. convert from the string to a number type.

To fix this you need to have a forEach loop which does the type conversion like:

data.forEach(function(d) {
   d["Amount Spent"] = +d["Amount Spent"].trim().replace(/\$/g, "").replace(/\,/g, "");
});

where,

the .trim() function removes any extra spaces before/after the text

the .replace(/\$/g, "") removes any $ signs

the .replace(/\,/g, ""); removes any commas

Here is a block with a working example with limited amount of data: https://bl.ocks.org/akulmehta/4ae4564a66c0869c1d9065cd8e73a586/