0
使用d3.js,我试图创建一系列SVG组(即<g>
元素),并为数组数组中的每个数字创建一个<g>
元素。每个<g>
元素本身应该包含<rect>
和<text>
。下面的代码在我看来应该这样做,但是当我检查<svg>
元素(在Chrome和Firefox中)时,它包含<rect>
元素和<text>
元素,它们直接位于<svg>
元素内,没有看到<g>
元素。无法创建SVG组
HTML页面最初只包含一个空的<svg>
元素。 dataset
只是一个简单的数字数组。
var svg = d3.select("svg"); svg.selectAll("g") .data(dataset) .enter() .call(function(g) { g.append("rect") .attr("x", (d, i) => xScale(i)) .attr("y", d => h - yScale(d)) .attr("width", xScale.rangeBand()) .attr("height", d => yScale(d)) .attr("fill", d => "rgb(0,0," + (d*10) + ")") .on('click', d => console.log(d)) .on('mouseover', function() { d3.select(this) .attr('fill', 'orange'); }) .on('mouseout', function(d) { d3.select(this) .transition() .duration(250) .attr("fill", d => "rgb(0,0," + (d*10) + ")") }); }) .call(function(g) { g.append('text') .text(d => d) .attr('class','label') .attr("x", (d, i) => xScale(i) + xScale.rangeBand()/2) .attr("y", d => h - yScale(d) + 14); });