1
votes

I'm trying to color the circles per a .csv data, column "COLOR". The "COLOR" includes "red", "yellow" , "green" -but right now the colors are not transferring... just the default black...

var col = function(d) {return d.COLOR};

svg.selectAll(".dot")
      .data(data)
    .enter().append("circle")
      .attr("class", "dot")
      .attr("r", 15)
      .attr("cx", xMap)
      .attr("cy", yMap)
      .style("fill", col)
      .style("opacity", ".5")
      .on("mouseover", function(d) {
          tooltip.transition()
               .duration(200)
               .style("opacity", .9);
          tooltip.html(d["Cereal Name"] + "<br/> (" + xValue(d)
            + ", " + yValue(d) + ")")
               .style("left", (d3.event.pageX + 5) + "px")
               .style("top", (d3.event.pageY - 28) + "px");

 data.forEach(function(d) {
    d.POPULATION = +d.POPULATION;
    d.REVENUE = +d.REVENUE;
    d.COLOR = +d.COLOR;

enter image description here

enter image description here

1
Can you provide a demo?Ofisora
I dont see any issues in this...one possibility could be that d.COLOR is not present in the data.Cyril Cherian
@cyril : I added a bit more detail showing the respective csv file along with the code which pulls the COLOR data from the file. am I missing something here? thanks!aiwan

1 Answers

3
votes

Your COLOR values in your CSV contain quotation marks " which will be part of the parsed strings in data. Therefore, you end up with attribute values like fill=""yellow"" which is not valid. Hence, the black default color.

One way around this might be to get rid of the quotation marks in the CSV itself. If this is not feasible, you might adjust your color accessor function col to something like the following:

var col = function(d) {return d.COLOR.substring(1, d.COLOR.length - 1)}; 

Have a look at this working demo:

var data = [{ COLOR: '"yellow"'}];

var col = function(d) { return d.COLOR.substring(1, d.COLOR.length - 1); };

d3.select("body").append("svg")
  .selectAll("circle")
  .data(data)
  .enter().append("circle")
    .attr("cx", 100)
    .attr("cy", 100)
    .attr("r", 10)
    .attr("fill", col);
<script src="https://d3js.org/d3.v4.js"></script>