我是d3 js的新手,我试图在力模拟的帮助下创建一个气泡图。 但是我创建了气泡但却无法在气泡上显示标签。以下是我的代码,对此代码的任何建议对我都有很大的帮助。
提前感谢
<html>
<head>
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<script>
var width = 1500;
var height = 1000;
var color = d3.scaleOrdinal(d3.schemeCategory10);
var canvas = d3.select("body")
.append("svg")
.attr("width",width)
.attr("height",height).
append("g")
.attr("transform","translate(0,0)");
var radiusScale = d3.scaleSqrt().domain([0,130000]).range([10,100])
var simulation = d3.forceSimulation()
.force("x",d3.forceX(width/2).strength(0.05))
.force("y",d3.forceY(height/2).strength(0.05))
.force("collide",d3.forceCollide(function(d){ return radiusScale(d.value)+1;}))
d3.queue().
defer(d3.csv,"historylogs.csv").await(ready);
function ready(error,datapoints){
console.log(datapoints);
datapoints = datapoints.map(function(d){ d.value = +d["size_kw"]; return d; });
datapoints = d3.nest()
.key(function(d) { return d.install_type;})
.rollup(function(d) {
return d3.sum(d, function(g) {return g.value; });
}).entries(datapoints);
console.log(datapoints);
var nodes = canvas.selectAll("g")
.data(datapoints)
.enter()
.append("g");
var circles= nodes
.append("circle")
.attr("r",function(d){ return radiusScale(d.value);} )
.attr("fill",function(d) { return color(d.value);})
.attr("opacity",0.5)
//.attr("dx", function(d){return d.key})
//.text(function(d){return d.key})
//.on('mouseover',function(d){})
var text= nodes
.append("text")
.attr("text-anchor", "middle")
.text(function(d){ return d.key; })
.style({
"fill":"black",
"font-family":"Helvetica Neue, Helvetica, Arial, san-serif",
"font-size": "12px"
});
simulation.nodes(datapoints).on('tick',ticked);
function ticked(){
circles.attr("cx",function(d){ return d.x;})
.attr("cy",function(d){ return d.y;});
//text.attr("x",function(d){ return d.x;})
//.attr("y",function(d){ return d.y;});
}
}
`
答案 0 :(得分:0)
在创建用于分组圆和文本元素的<g>
元素后,只需设置group元素的transform
属性即可更新两个元素的位置。因此,请更改您的滴答功能,如下所示。
function ticked() {
nodes.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
}