我有一个数据集显示在 D3JS 散点图上。基本上,数据集的点是(x,y,类别),我想将“类别 A”绘制为橙色圆圈,将“类别 B”绘制为蓝色三 Angular 形。
[今天]颜色还可以,但所有点都是圆形:
[ ... ]
var color = d3.scale.ordinal()
.domain(["Category A", "Category B"])
.range(["#f76800", "#000066"]);
// draw dots
svg.selectAll(".dot")
.data(data)
.enter().append("circle")
.attr("class", "dot")
.attr("r", 7)
.attr("cx", xMap)
.attr("cy", yMap)
.style("fill", function(d) {
return color(d.category);
;})
[ ... ]
我找到了这个帖子Triangle scatter plot with D3.js所以我正在尝试 - 但没有取得多大成功 - 类似:
[ ... ]
var color = d3.scale.ordinal()
.domain(["Category A", "Category B"])
.range(["#f76800", "#000066"]);
// draw dots
svg.selectAll(".dot")
.data(data)
.enter().append((d.category == "Category A") ? "circle":"path")
.attr((d.category == "Category A") ? "CIRCLE attr":"TRIANGLE attr")
.style("fill", function(d) {
return color(d.category);
;})
[ ... ]
这是一个合理的尝试吗?
编辑:尝试
[ ... ]
svg.selectAll(".dot")
.data(data)
.enter().append((d.category == "A") ? "path":"circle")
.attr((d.category=="A") ? ({"d":d3.svg.symbol().type("triangle-up"), "transform":"translate(" + xMap + "," + yMap + ")"}):({"class":"dot", "r":7, "cx":xMap, "cy":yMap}))
.style("fill", function(d) {
return color(d.category);
;})
.style("opacity", .95 )
.style("stroke-width", function(d) {
if (d.category == "A") {return 0.95}
else { return 0 }
;})
[ ... ]
结果:Firebug 控制台中的“ReferenceError:d 未定义”
编辑 2 - 数据子集
希望有帮助:查看完整代码,这是实际网站:http://www.foolset.com/SNES.php?Jeu=Whirlo 。请注意,此处出于教育目的而提到的字段“d.category”实际上是“d.site”。
数据子集:数据来自MySQL请求,字段包括:“prix”(对于Y值)、“date”(对于X值)和“site”,即上面的类别。其他字段在这里无关紧要。请在此处查找数据子集:http://www.pastebin.com/khdXCSNx
最佳答案
您需要提供对 .append()
和 .attr()
的回调,而不是表达式,就像调用 .style() 所做的那样
。因为在调用函数时表达式只会被计算一次,所以它们将为所有点提供常量值。这就是为什么颜色(即 style("fill", function() {})
)可以,但形状不行。此外,它是对提示 d
未定义的 ReferenceError 的解释。
尽管回调对于 .append()
来说效果很好,但我怀疑是否有一个简单的解决方案可以以这种方式设置属性。
svg.selectAll(".dot")
.data(data)
.enter().append(function(d) { // This needs to be a callback, too.
var type = d.category == "Category A" ? "circle" : "path";
// In this case, you need to create and return the DOM element yourself.
return document.createElementNS("http://www.w3.org/2000/svg", type);
})
.attr(
// Not sure, if there is an easy solution to setting the attributes.
)
.style("fill", function(d) { // This one already uses a callback function.
return color(d.category);
;})
你的方法似乎过于复杂,感觉像是一条死胡同。我建议坚持使用您链接到的示例,该示例使用支持圆形和三 Angular 形的d3.svg.symbol()
路径生成器> 通过设置appropriate type .
svg.selectAll(".dot")
.data(data)
.enter().append("path")
.attr("d", d3.svg.symbol().type(function(d) {
return d.category == "Category A" ? "triangle-up" : "circle";
}))
.attr("transform", function(d) {
return "translate(" + xMap(d) + "," + yMap(d) + ")";
});
关于javascript - D3JS - 在散点图中显示圆形和三 Angular 形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34466262/