CSV颜色数据无法呈现

时间:2017-09-10 05:57:37

标签: javascript csv d3.js colors

我试图根据.csv数据,列" COLOR"为圆圈着色。 " COLOR"包括" red"," yellow" ,"绿色" - 但是现在颜色没有转移......只是默认的黑色......

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 个答案:

答案 0 :(得分:3)

您的CSV中的COLOR值包含引号",它将成为data中已解析字符串的一部分。因此,您最终会得到fill=""yellow""这样无效的属性值。因此,黑色默认颜色。

解决此问题的一种方法可能是删除CSV本身中的引号。如果这不可行,您可以将颜色访问器函数col调整为如下所示:

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

看看这个有用的演示:

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>

相关问题