问题描述
我有一个D3散点图,我正尝试添加一个选项,以根据变量的值将图表显示为圆形或图像.
I have a D3 scatter chart and I'm trying to add the option to view the chart as circles or as images, based on the value of a variable.
目前,我可以查看任一图表(只要我将其中之一注释掉即可)
At the moment I can view the chart as either (as long as I comment one of them out)
以下是添加图像的代码:
Here is the code for appending the images:
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";//或点"
我正在尝试做类似的事情:
I was trying to do something like:
if (displaytype == "image") { return
//....code for images.....
else { return
//....code for dots.....
}
任何帮助我们弄清楚这一点的帮助将不胜感激
Any help on trying to figure this out would be much appreciated
谢谢
推荐答案
您使用if/else的方法没有错.您需要记住的是,点和图像是我称之为点"的等效表示.这意味着选择不应该将圆与图像区分开:它应该选择点.这可以通过使用类选择器而不是标签选择器来完成.
Your approach of using if/else is not wrong. What you need to keep in mind is that dots and images are equivalent representations of what I'll call "points". This means that the selection shouldn't distinguish circles from images: it should just select points. This could be done by using a class selector instead of a tag selector.
在您的情况下,代码使用两个不同的类选择器: .dot
和 .image
.代替 svg.selectAll('.image')
和 svg.selectAll('.dot')
,您可以使用 svg.selectAll('.point')
.因此:
In your case, the code is using two different class selectors: .dot
and .image
. Instead of svg.selectAll('.image')
and svg.selectAll('.dot')
, you could use svg.selectAll('.point')
for both of them. Thus:
const enterSelection = svg.selectAll(".point").data(data).enter();
if (displaytype == "image") {
enterSelection
.append("svg:image")
.attr("class", "point")
.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;
});
} else {
enterSelection
.append("circle")
.attr("class", "point")
.attr("r", 3.5)
.attr("cx", xMap)
.attr("cy", yMap)
.style("fill", function (d) {
return color(cValue(d));
});
}
这篇关于D3根据变量有条件地附加图像OR圆元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!