我在D3JS散点图上显示了一个数据集。基本上,数据集的点是(x,y,类别),我想绘制"类别A"作为橙色圆圈和" B类"作为蓝色三角形。
[TODAY]颜色没问题,但所有点都是圆圈:
[ ... ]
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 }
;})
[ ... ]
结果:" ReferenceError:d未定义"在Firebug控制台中
编辑2 - 数据子集
可以提供帮助:要查看完整代码,请访问以下网址:http://www.foolset.com/SNES.php?Jeu=Whirlo。注意字段" d.category"这里提到的用于教育目的,实际上是" d.site"。
数据子集:数据来自MySQL请求,字段包括:" prix" (对于Y值),"日期" (对于X值)," site"即上面的类别。其他领域在这里无关紧要。请在此处找到数据子集:http://www.pastebin.com/khdXCSNx
答案 0 :(得分:2)
而不是表达式,您需要向.append()
和.attr()
提供回调,就像调用.style()
一样。因为只有在调用函数时才会对表达式求值,所以这些表达式将为所有点提供常量值。这就是为什么颜色,即style("fill", function() {})
,没有,而形状不是。此外,它是对ReferenceError抱怨d
为undefined
的解释。
虽然回调对.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);
;})
你的方法似乎过于复杂,感觉像是一条死路。我建议坚持你链接到的示例,它通过设置appropriate type来使用支持 circle 和三角形的d3.svg.symbol()
路径生成器
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) + ")";
});