【问题标题】:D3 Pie chart not showing legendD3饼图不显示图例
【发布时间】:2019-12-24 14:33:56
【问题描述】:

图例是在g 标记中创建的。我怎样才能像这个例子一样把它拉出来。 右侧有颜色条。

代码

    this.svg = d3.select("#airlineChart").select("svg");
     this.mainContainer = this.svg
          .append("g")
          .attr("transform", `translate(${this.radius},${this.radius})`)

;
    private drawSlices() {
    this.slices = this.mainContainer
      .selectAll("path")
      .remove()
      .exit()
      .data(this.pie(this.pieairline))
      .enter()
      .append("g")
      .append("path")
      .attr("d", this.arc);

    this.slices
      .append("rect") // make a matching color rect
      .attr("class", "pieLegend")
      .attr("width", 10)
      .attr("height", 10)
      .append("text") // add the text
      .text(function(d) {
        return d.data.name;
      })
      .style("font-size", 12)
      .attr("y", 10)
      .attr("x", 11);


    this.slices
      .attr("fill", (d, i) => this.color(i))
      .attr("stroke", "black")
      .style("stroke-width", "0px");
      }

slice 只是带​​有任何datatype 的计划变量

当前视图

控制台

【问题讨论】:

  • 我们需要更多代码。你能告诉我们,this.slices 是在哪里定义的吗?
  • @Sirko,问题已更新。

标签: angular d3.js pie-chart


【解决方案1】:

d3 中的方法链返回的元素通常是您在该链中创建的最后一个元素。所以下面会给你一个创建的<path>-elements的引用:

this.slices = this.mainContainer
  .selectAll("path")
  .remove()
  .exit()
  .data(this.pie(this.pieairline))
  .enter()
  .append("g")
  .append("path")
  .attr("d", this.arc);

在下一次调用中,您将进一步的 <rect><text> 元素附加到此 <path>,将子节点分配给其 DOM 表示。

快速解决方法是将所有元素直接附加在相应的<g>-element 下:

this.slices = this.mainContainer
  .selectAll("path")
  .remove()
  .exit()
  .data(this.pie(this.pieairline))
  .enter()
  .append("g")

// append the circle segment
this.slices
  .append("path")
  .attr("d", this.arc)
  .attr("fill", (d, i) => this.color(i))
  .attr("stroke", "black")
  .style("stroke-width", "0px");

// append the rect element
this.slices
  .append("rect") // make a matching color rect
  .attr("class", "pieLegend")
  .attr("width", 10)
  .attr("height", 10)
  .attr("fill", (d, i) => this.color(i))
  .attr("stroke", "black")
  .style("stroke-width", "0px");

// append the text element
this.slices
  .append("text") // add the text
  .text((d) => d.data.name )
  .style("font-size", 12)
  .attr("y", 10)
  .attr("x", 11);

旁注:我认为您应该将图例添加到不同的容器元素中。这使得使用transform() 移动它更容易,然后将其拆分为许多<g> 元素。要做到这一点,基本上您需要将数据绑定到第二组元素(以您已经做过的相同方式)。然后,第二组只包含 <rect><text> 元素,但不包含圆段。

【讨论】:

  • Sirko,我把它分开了,但它又没有显示图例,在控制台中,它只显示第一个值而不是前面
  • @user12552117 你能准备一个小小提琴来展示你的其余代码吗?
  • @user12552117 对不起,但是 stackblitz 似乎在我所有的浏览器中都有问题,所以我无法查看生成的 HTML 代码。
  • 我只是在小提琴中添加了代码,但它没有运行,至少你得到了代码。 link
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多