简体   繁体   English

如何通过在svg元素上调整大小来使文本的位置动态化?

[英]How do I make the position of the text dynamic with resize on an svg element?

I am creating a sort of bar chart and I am trying to include data labels. 我正在创建一种条形图,并且尝试包含数据标签。 I have drawn the text containing the appropriate values but it doesn't respond well to being resized. 我已经绘制了包含适当值的文本,但是它对于调整大小并不能很好地响应。 Instead of moving with the bar it just stays still till the page is refreshed. 它不会移动栏,而是保持静止直到刷新页面。

Note that the numbers should be right above the green and red bars: 请注意,数字应在绿色和红色条的正上方:

图片

this.svg.selectAll("text.dataLabels")        
    .data(viewModel.dataPoints)
    .enter()
    .append("text")
    .attr("class","dataLabels")
    .attr({
        y: (dataPoint: BarChartDataPoint) => yScale(<number>dataPoint.value)-BarChart.Config.dataLabelShift.vertical,
        x: (dataPoint: BarChartDataPoint) => xScale(dataPoint.category)+BarChart.Config.dataLabelShift.horizontal
    })
    .attr("text-anchor", "middle")
    .text((dataPoint: BarChartDataPoint) => <string>dataPoint.value)
    .style({
        'font-family': 'sans-serif',
        'font-weight':'bold',
        'fill': 'grey'
    }); 

Instead of working directly with the parent svg object and appending a text element directly onto it, instead I create a separate element: 与其直接使用父svg对象并直接在其上附加文本元素,不如创建一个单独的元素:

 private dataLabels: d3.Selection<SVGElement>;
    this.dataLabels = this.svg
            .append('g')
            .classed('dataLabels',true)

I then appended the text elements to a new object: 然后,我将文本元素附加到新对象:

let dataLabelEl = this.dataLabels
                .selectAll('text.dataLabels')
                .data(viewModel.dataPoints);

            dataLabelEl
                .enter()
                .append('text')
                .classed('dataLabels', true);

            dataLabelEl
                .attr({
                    y: (dataPoint) => yScale(<number>dataPoint.value)-BarChart.Config.dataLabelShift.vertical,
                    x: (dataPoint) => xScale(dataPoint.category)+BarChart.Config.dataLabelShift.horizontal
                })
                .attr("text-anchor", "middle")
                .text((dataPoint) => <string>dataPoint.value)
                .style({
                    'font-family': 'sans-serif',
                    'font-weight':'bold',
                    'fill': 'grey'
                });

This works! 这可行!

您可以设置文本的x和y位置,并且永远不会使调整大小后的干扰遵循链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM