2017-06-03 11 views
-1

円を描いたこのコードは、各円の内側にテキストを置く必要があります。円の各要素にどのように一定のサイズを入れることもできます。 ありがとうございます。を使用して円の真ん中にテキストを配置します。 d3.js

svg = d3.select(selector) 
    .append('svg') 
    .attr('width', width) 
    .attr('height', height); 

    // Bind nodes data to what will become DOM elements to represent them. 
    bubbles = svg.selectAll('.bubble') 
    .data(nodes, function (d) { return d.id; }); 

    // Create new circle elements each with class `bubble`. 
    // There will be one circle.bubble for each object in the nodes array. 
    // Initially, their radius (r attribute) will be 0. 



    bubbles.enter().append('circle') 
    .classed('bubble', true) 
    .attr('r', 0) 
    .attr('fill', function (d) { return fillColor(d.group); }) 
    .attr('stroke', function (d) { return d3.rgb(fillColor(d.group)).darker(); }) 
    .attr('stroke-width', 2) 
    .on('mouseover', showDetail) 
    .on('mouseout', hideDetail); 


    // Fancy transition to make bubbles appear, ending with the 
    // correct radius 
    bubbles.transition() 
    .duration(2000) 
    .attr('r', function (d) { return d.radius; }); 

答えて

0

2つの要素(円とテキスト)で構成されるため、バブルごとにグループ要素を作成することをお勧めします。その後

// Bind nodes data to what will become DOM elements to represent them. 
bubbles = svg.selectAll('.bubble') 
    .data(nodes, function(d) { 
    return d.id; 
    }) 
    .enter() 
    .append('g') 
    .attr("transform", d => `translate(${d.x}, ${d.y})`) 
    .classed('bubble', true) 
    .on('mouseover', showDetail) 
    .on('mouseout', hideDetail) 

、円やテキストは追加することができます。

circles = bubbles.append('circle') 
    .attr('r', 0) 
    .attr('stroke-width', 2) 


texts = bubbles.append('text') 
    .attr('text-anchor', 'middle') 
    .attr('alignment-baseline', 'middle') 
    .style('font-size', d => d.radius * 0.4 + 'px') 
    .attr('fill-opacity', 0) 
    .attr('fill', 'white') 
    .text(d => d.text) 

// Fancy transition to make bubbles appear, ending with the 
// correct radius 
circles.transition() 
    .duration(2000) 
    .attr('r', function(d) { 
    return d.radius; 
    }); 

テキストを表示/非表示にするために、それならば、あなたはfill-opacity属性を使用してテキストを非表示にする必要があるとき0にそれを設定し、1することができます示すべきである:

function showDetail(d, i) { 
    d3.select(this.childNodes[1]).attr('fill-opacity', 1) 
} 

function hideDetail(d, i) { 
    d3.select(this.childNodes[1]).attr('fill-opacity', 0) 
} 

例:https://jsfiddle.net/r880wm24/

+0

感謝を!しかし、私の実際の例では動作しません.. http://plnkr.co/edit/2BCVxQ5n07Rd9GYIOz1c?p=preview – yavg

関連する問題