D3.js D3基于变量有条件地追加图像或圆元素
我有一个D3散点图,我试图添加一个选项,根据变量的值,将图表视为圆形或图像 目前,我可以查看图表(只要我将其中一个注释掉) 以下是用于附加图像的代码:D3.js D3基于变量有条件地追加图像或圆元素,d3.js,D3.js,我有一个D3散点图,我试图添加一个选项,根据变量的值,将图表视为圆形或图像 目前,我可以查看图表(只要我将其中一个注释掉) 以下是用于附加图像的代码: svg.selectAll(".image") .data(data) .enter() .append("svg:image") .attr("x", xMap) .attr("y", yMap) .attr("width&q
svg.selectAll(".image")
.data(data)
.enter()
.append("svg:image")
.attr("x", xMap)
.attr("y", yMap)
.attr("width", logosize)
.attr("height", logosize)
.attr('transform', function(d) { return 'translate('+ -d.logosize/2 +',' + -d.logosize/2 + ')'; } )
.attr("xlink:href", function(d) {
return d.brand_image;
})
以及添加点的代码:
svg.selectAll(".dot")
.data(data)
.enter().append("circle")
.attr("class", "dot")
.attr("r", 3.5)
.attr("cx", xMap)
.attr("cy", yMap)
.style("fill", function(d) {
return color(cValue(d));
})
变量为var displaytype=“image”//或“dot”
我试着做一些事情,比如:
if (displaytype == "image") { return
//....code for images.....
else { return
//....code for dots.....
}
如果您能帮我解决这个问题,我们将不胜感激
谢谢你使用if/else的方法没有错。你需要记住的是,点和图像是我所说的“点”的等价表示。这意味着选择不应该区分圆和图像:它应该只选择点。这可以通过使用类选择器而不是标记选择器来实现 在您的例子中,代码使用两个不同的类选择器:
.dot
和.image
。代替svg.selectAll('.image')
和svg.selectAll('.dot')
,您可以将svg.selectAll('.point')
用于两者。因此:
const entreselection=svg.selectAll(“.point”).data(data.enter();
如果(显示类型=“图像”){
企业选择
.append(“svg:image”)
.attr(“类”、“点”)
.attr(“x”,xMap)
.attr(“y”,yMap)
.attr(“宽度”,标识大小)
.attr(“高度”,logosize)
.attr(“转换”,函数(d){
返回“translate(“+-d.logosize/2+”,“+-d.logosize/2+”);
})
.attr(“xlink:href”,函数(d){
返回d.brand_图像;
});
}否则{
企业选择
.附加(“圆圈”)
.attr(“类”、“点”)
.attr(“r”,3.5)
.attr(“cx”,xMap)
.attr(“cy”,yMap)
.样式(“填充”,功能(d){
返回颜色(c值(d));
});
}
使用if/else的方法没有错。你需要记住的是,点和图像是我所说的“点”的等价表示。这意味着选择不应该区分圆和图像:它应该只选择点。这可以通过使用类选择器而不是标记选择器来实现
在您的例子中,代码使用两个不同的类选择器:.dot
和.image
。代替svg.selectAll('.image')
和svg.selectAll('.dot')
,您可以将svg.selectAll('.point')
用于两者。因此:
const entreselection=svg.selectAll(“.point”).data(data.enter();
如果(显示类型=“图像”){
企业选择
.append(“svg:image”)
.attr(“类”、“点”)
.attr(“x”,xMap)
.attr(“y”,yMap)
.attr(“宽度”,标识大小)
.attr(“高度”,logosize)
.attr(“转换”,函数(d){
返回“translate(“+-d.logosize/2+”,“+-d.logosize/2+”);
})
.attr(“xlink:href”,函数(d){
返回d.brand_图像;
});
}否则{
企业选择
.附加(“圆圈”)
.attr(“类”、“点”)
.attr(“r”,3.5)
.attr(“cx”,xMap)
.attr(“cy”,yMap)
.样式(“填充”,功能(d){
返回颜色(c值(d));
});
}
您还可以使用父级g
来保存圆圈/图像,这样可以在不使用新的selectAll().data().enter().append()循环的情况下,将圆圈与图像交换,反之亦然。此外,如果g
定位了所有内容,它将进一步简化两者之间的交换-但不确定这是否超出OP的最终目标范围。您还可以使用父g
来保存圆/图像,这将允许在不使用新的selectAll().data().enter().append()的情况下将圆交换为图像,反之亦然
循环。此外,如果g
定位了所有内容,则将进一步简化两者的交换-但不确定这是否超出OP的最终目标范围。