簡體   English   中英

CSV顏色數據無法呈現

[英]CSV color data not rendering

我正在嘗試根據.csv數據,“COLOR”列為每個圓圈着色。 “顏色”包括“紅色”,“黃色”,“綠色” - 但是現在顏色沒有轉移...只是默認的黑色......

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;

在此輸入圖像描述

在此輸入圖像描述

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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM