2016-08-18 54 views
1

我正在使用d3在angular2中制作饼图组件,并且在尝试向图表中添加文本时我陷入了困境。我可以在开发人员工具中的元素资源管理器中看到文本,但它没有显示在图表上。我有一种感觉,他们可能真的很愚蠢,但我无法弄清楚它可能是什么。我的代码如下。D3饼图标签数据不能正常工作

showChart() { 
    let widthRatio = 4; 
    let heightRatio = 3; 
    let radius = Math.min(widthRatio, heightRatio)/2; 

    let color = d3.scaleOrdinal(d3.schemeCategory20b); 

    let svg = d3.select('#' + this.chartId) 
     .append('svg') 
     .attr('width', '100%') 
     .attr('height', '100%') 
     .attr('viewBox', '0 0 ' + widthRatio + ' ' + heightRatio) 
     .append('g') 
     .attr('transform', 'translate(' + (widthRatio/2) + ',' + (heightRatio/2) + ')'); 

    let arc = d3.arc() 
     .innerRadius(0) 
     .outerRadius(radius); 

    let labelArc = d3.arc() 
     .innerRadius(radius - 40) 
     .outerRadius(radius - 40); 

    let pie = d3.pie() 
     .value((d) => { return d.count; }) 
     .sort(undefined); 

    let g = svg.selectAll('.arc') 
     .data(pie(this.chartData)) 
     .enter() 
     .append('g') 
     .attr('class', 'arc'); 

    g.append('path') 
     .attr('d', arc) 
     .style('fill', (d) => { return color(d.data.label); }); 

    g.append('text') 
     .attr('transform', (d) => { return 'translate(' + labelArc.centroid(d) + ')'; }) 
     .attr('dy', '.35em') 
     .text((d) => { return 'test'; }); 
} 

感谢您的任何帮助提前。

回答

1

解决了这个问题。我使用widthRatio和heightRatio来控制图表在调整大小时的纵横比,但这意味着标签文本正在获取3和4的坐标,导致它不显示。在我的情况下,为了解决这个问题,我更改了代码,以便宽度和高度由父容器的宽度和高度设置,而父容器的宽度和高度又由引导网格控制。

let width = parseInt(d3.select('#' + this.parentContainerId).style('width')); 
let height = parseInt(d3.select('#' + this.parentContainerId).style('height'));