我正在尝试根据 .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;
最佳答案
您的 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/