如何在D3.js中使用现有的“ <g> =组”创建单个“ <g> =组”

时间:2019-12-02 16:11:01

标签: javascript d3.js svg

我是“ d3.js”中的新手,并且我正在尝试实现一个“甜甜圈图”,其右侧带有一些描述信息,我将它们分别分组为<g class="device-info">并且我希望所有创建的群组<g class="device-info">都属于一个群组<g class="device-desc">,但是我在执行此操作时遇到了麻烦,我们将不胜感激。

这是我的代码:

var colors = ["#249AFF", "#CFDCE5", '#76D3C1']


var data1 = {online: 1430,offline:342, test: 200};

var pie = d3.pie()
  .value(function(data1) {return data1.value })
var data_ready = pie(d3.entries(data1))

var arc = d3.arc()
.innerRadius(60)
.outerRadius(70)
.startAngle(data_ready => data_ready.startAngle)
.endAngle(data_ready => data_ready.endAngle)

var svg = d3.select(".svg")
.attr('width', 350)
.attr('height', 220)

svg.selectAll('path')
.data(data_ready)
.enter()
.append('path')
.attr('d', arc)
.attr('fill', (d, i) => colors[i])
.attr('stroke', 'none')
.attr('transform', "translate(100,130)")


var groups = svg.selectAll(".groups")
    .data(data_ready)
    .enter()
    .append("g")
    .attr("class", "device-info")
    .attr('transform', ( d, i ) =>  {
       i *= 30
       return `translate(90, ${i})` 
    })


    groups.append('circle')
    .attr('fill', (d,i) => colors[i])
    .attr('transform', `translate(147, 0)`)
    .attr('r','5')
    .attr('cx', -20)
    .attr("cy", ( d, i ) =>  {
        return i * 19
    })

    groups.append('text')
    .text(data1 => data1.data.key)
    .attr('fill', function(d,i){ return(colors[i]) })
    .attr('class', 'devices-status')
    .attr('transform', `translate(150, 5)`)
    .style('text-transform', 'capitalize')
    .style('font-size', 14)
    .attr("dx", -15 )
    .attr("dy", ( d, i ) =>  i * 20)


    groups.append('text')
    .text(data1 => data1.data.value + " devices")
    .attr('fill', 'white')
    .style('font-size', 15)
    .attr('class', 'devices')
    .attr('transform', `translate(140, 5)`)
    .attr("dx", -15 )
    .attr("dy", ( d, i ) =>  {
        i += 2;
        return i * 12
    })


    svg.append("text")
    .text('Devices by status')
    .attr('transform' , "translate(10, 25)")
    .style('text-transform', 'uppercase')
    .style('fill', 'rgb(255,255,255)')
    .style('font-size', 15)

    svg.append("text")
    .text(`Total devices ${1772}`)
    .attr('transform' , "translate(10, 45)")
    .style('text-transform', 'capitalize')
    .style('fill', 'rgba(255,255,255, .6)')
    .style('font-size', 13)

这是一个演示: Click here

1 个答案:

答案 0 :(得分:2)

只需将容器组附加到具有相应类的SVG ...

var containerGroup = svg.append("g")
    .attr("class", "device-desk");

然后将groups附加到该容器组:

var groups = containerGroup.selectAll(".groups")
    .data(data_ready)
    .enter()
    //etc...