首页 > 代码库 > [D3] SVG Graphics Containers and Text Elements in D3 v4

[D3] SVG Graphics Containers and Text Elements in D3 v4

SVG is a great output format for data visualizations because of its scalability, but it comes with some idiosyncrasies and unique challenges. In this lesson we’ll learn how to use graphics containers, the SVG equivalent of a div, as well as text elements for displaying, you guessed it, text.

 

var scores = [  { name: ‘Alice‘, score: 96 },  { name: ‘Billy‘, score: 83 },  { name: ‘Cindy‘, score: 91 },  { name: ‘David‘, score: 96 },  { name: ‘Emily‘, score: 88 }];const bars = d3.select(‘.chart‘)    .append(‘svg‘)        .attr(‘width‘, 300)        .attr(‘height‘, 300)        .style(‘background‘, ‘white‘)    .selectAll(‘g‘) // ‘g‘ works as canvas on svg    .data(scores)    .enter()        .append(‘g‘)        .attr(‘transform‘, (d, i) => ‘translate(0, ‘ + i * 33 + ‘)‘);bars.append(‘rect‘)    .attr(‘width‘, d => d.score)    .attr(‘class‘, ‘bar‘);bars.append(‘text‘)    .text(d => d.name)      .attr(‘y‘, 20);

 

 

<iframe style="width: 100%; height: 500px;" src="https://embed.plnkr.co/NRYm5dxmM4kZGt8XKBNU/" width="320" height="240"></iframe>

[D3] SVG Graphics Containers and Text Elements in D3 v4