【问题标题】:Add text at end of needle of Half pie chart - D3 with Angular在半饼图针的末尾添加文本 - D3 with Angular
【发布时间】:2021-10-11 20:29:02
【问题描述】:

我在 Angular 12 应用程序中使用 D3.js 制作半饼图。我添加了针,但我希望在针的末尾有文本以显示图像中的值 Needle with Value

我得到了 needle,但无法在 needle 末尾呈现值。

我的代码

this.svg = d3
          .select('div#pie')
          .append('svg')
          .attr('width',this.svgWidth)
          .attr('height',this.svgHeight)
          .attr('id','pie-svg') 
          .append('g')
          .attr('class','ps')
          .attr(
            'transform',                
            'translate('+this.svgWidth/2+',115)');
                       
this.colorRanges = d3.scaleOrdinal()
.domain(['a', 'b', 'c'])
.range(this.colors)    

this.pie = d3
.pie()
.startAngle(-90 * (Math.PI / 180))
.endAngle(90 * (Math.PI / 180))
.value((d: any,i:number) => d[1])
.sort((a:any, b:any) => d3.ascending(a[0], b[0]));

this.svg.selectAll('rect')  
.data(this.pie(Object.entries(this.pieData)))
.join('path')
.attr('d',
d3.arc().innerRadius(75).outerRadius(35))
.attr('fill', (d:any,i:number) => this.colorRanges(d3.schemeSet2[i]))
.attr('stroke','none')
.style('stroke-width','1px')
.style('opacity',1);    

this.svg
  .selectAll('.needle')
  .data([0])
  .enter()
  .append('line')
  .attr('x1', -10)
  .attr('x2', -75)
  .attr('y1', 0)
  .attr('y2', 0)
  .classed('needle', true)
  .attr('transform', 'rotate(135)');      
  

我尝试从互联网上添加如下代码,但失败了。

var labelArc = this.svg.arc()
  .outerRadius(75)
  .innerRadius(35);

  this.svg.append("text")
  .attr("transform", function(d: any) {
  return "translate(" + labelArc.centroid(d) + ")"; })
  .attr("dy", ".35em")
  .text("75");

由于我是 D3 和 Angular 的新手,因此无法继续。

有人可以帮忙把文字放在针头上吗?

【问题讨论】:

    标签: javascript angular typescript d3.js charts


    【解决方案1】:

    您可以尝试添加一个插入新图形的新“g”,该位置可能靠近针头,但需要一些解决方法。

    【讨论】:

    • 如果您提供一些代码示例会很有帮助。
    • this.svg.selectAll("circle1") .data(data) .enter() .append("circle") .attr("fill", "#7B1E99") .attr("r", 3) .style("opacity", 0.5) .html("<span> Text: </br>" + d.value + "</span>") 这基本上是加了一个圈子,把提到的html内容放在圈子里面。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    • 2013-04-05
    • 1970-01-01
    • 1970-01-01
    • 2012-08-06
    • 1970-01-01
    • 2022-06-11
    相关资源
    最近更新 更多