0

I am trying to create a map visualization using d3. I have gotten the map to work and am trying to add points on the map. Depending on some other data in the CSV file (inspection results) I want certain points to have a different color. I can add the points using this code, but I cannot get the colors to come out correctly (there should be red ones, but all of them are green). I think it is a problem with how I'm trying to get the data out, or just a problem with my JavaScript in general. Any help would be appreciated. Thank you!

function colorr(d) {
  if (d == 0) {
    return "red";
  } else {
    return "green";
  }  
}

var dataset = []

//         load data about food
// https://stackoverflow.com/questions/47821332/plot-points-in-map-d3-javascript
// https://groups.google.com/forum/#!topic/d3-js/AVEa7nPCFAk
// https://stackoverflow.com/questions/10805184/show-data-on-mouseover-of-circle

d3.csv('data6.csv').then( function(data) {

    // don't know if this actually does anything...
    dataset=data.map(function(d) { return [+d["InspectionScore"],+d["Longitude"],+d["Latitude"]];});


    g.selectAll('circle')
      .data(data)
      .enter()
      .append('circle')
      .attr("cx",function(d) { return projection([d.Longitude,d.Latitude])[0]; }).merge(g)
      .attr("cy",function(d) { return projection([d.Longitude,d.Latitude])[1]; }).merge(g)
      .attr("r", .4)
      .attr("fill", d3.color(colorr(   function(d) { return d.InspectionScore }   ) ));
});
egg202
  • 3
  • 1
  • change the last line in the code to `.attr("fill", d => d3.color(colorr(d.InspectionScore))));` – jrook Oct 28 '18 at 20:50
  • And with this code, `dataset` is doing nothing! – jrook Oct 28 '18 at 20:51
  • @jrook it worked, thank you so much!! if you don't mind, can you explain the difference between my code and your code and why mine does not work? to be honest, i've never done any javascript / d3, so this code was created mostly through copy/paste and pattern matching – egg202 Oct 28 '18 at 21:17
  • I posted an answer. Please accept it if it solves the issue. Cheers! – jrook Oct 28 '18 at 21:29

1 Answers1

0

This can be resolved by changing the last line to:

.attr("fill", d => d3.color(colorr(d.InspectionScore))));

The reason this works is that d3's attr allows you to take the attribute value from a function. In this case you want to transform the data element to either red or blue. This is what the arrow function does in the above code. It is equivalent to :

.attr("fill", function(d) {
    return d3.color(colorr(d.InspectionScore));
    })

To get a deeper understanding of how D3 works, you can check the tutorials.

jrook
  • 3,459
  • 1
  • 16
  • 33