我遇到D3 joins的问题。我在气泡图上创建了一些圆圈。当用户点击“显示为地图”按钮时,我想将圆圈转换为地图,然后为每个圆圈添加标签。
目前点击处理程序会移动圈子,然后给我一个JavaScript错误,而不是添加标签:Uncaught TypeError: Object [object SVGCircleElement]... has no method 'append'
。我知道这是因为我的连接语法不正确,但我该如何解决呢?
我可以找到添加新D3元素的所有示例都适用于绑定新数据的情况 - 而不是已经存在已绑定数据的现有元素的情况。
这是我创建圈子的代码:
var circle = g.selectAll('.city')
.data(data).enter()
.append('circle')
.attr('class', 'city')
.attr('r', rfunc).attr("cy", 0)
.attr("cx", function(d, i) {
return rdist(d['dist']);
}).attr("transform", function(d, i) {
return "rotate(" + d.radial_pos + " 0 0)";
});
这是我的点击处理程序:
d3.select("#layout_geo").on("click", function() {
// Move the circles - this works OK.
var circles = d3.selectAll(".city")
.transition()
.duration(1300)
.attr('cx', function(d) {
return merc([d['lon'], d['lat']])[0] - 350;
}).attr('cy', function(d) {
return merc([d['lon'], d['lat']])[1] - 280;
});
// How to add text to each circle?
circles.append('text')
.attr('class', 'background')
.text(function(d) {
console.log(d.name + ', ' + d.city);
return d.name + ', ' + d.city;
})
.attr('cx', function() {
return ???;
}).attr('cy', function() {
return ???;
});
});
答案 0 :(得分:3)
此处的问题是circles
不是正常选择,而是transition。它们具有方便的remove()
功能,可以删除项目,但不能append
添加更多元素。
另一个问题是在<text>
属性中追加<circle>
元素是不正确的SVG。在这种情况下,您需要将<text>
和<circle>
放在g
元素like this中。代码中的相应更改将是:
d3.select("#layout_geo").on("click", function() {
// Assign the seleciton to circles
var circleG = d3.selectAll(".city");
circleG.transition()
.duration(1300)
.attr('transform', 'translate(-100, -50)'); // Ignoring the rotation.
// And append text to the selection
circleG.append('text')
.attr('class', 'background')
.attr('dx', '1em')
.text(function(d) {
console.log(d.name + ', ' + d.city);
return d.name + ', ' + d.city;
});
});
请注意,更改<circle>
属性时,transform
元素上的旋转会丢失。它可以由using two nested g elements with rotation on the outer one.