javascript - CSV 颜色数据未呈现

标签 javascript csv d3.js colors

我正在尝试根据 .csv 数据“颜色”列为圆圈着色。 “COLOR”包括“red”、“yellow”、“green”-但是现在颜色没有转移...只是默认的黑色...

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

最佳答案

您的 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>

关于javascript - CSV 颜色数据未呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46137713/

相关文章:

c - 段错误、解析、C

javascript - 使用javascript将CSV文件读入数组

d3.js - 使用 Vega 生成 3D 曲面图?

javascript函数是对象吗?

javascript - 如何单击一个 div 并让它更改其他 div 的尺寸,然后再次单击后更改回来

javascript - AngularJS:组件不会显示通过 HTTP 加载的数据

R:导入列名称包含空格的 CSV

javascript - Bokeh 从 CustomJS 获取值(更改数据源中的值)

d3.js - 将超链接添加到可折叠树上的节点文本

javascript - SVG 文本在 IE 中消失,直到我点击它