D3在工具提示中添加甜甜圈图表

D3 adding donut chart within a tooltip

本文关键字:甜甜圈 添加 工具提示 D3      更新时间:2023-09-26

我试图在工具提示中显示一个甜甜圈图。我认为这将只是简单地添加函数名或创建图表内。html(),但事实并非如此可悲。谁能告诉我我哪里做错了?

下面是我的代码:

tooltip.select('.label').html(donutChart());

function donutChart(){
    var dataset = {
      hddrives: [20301672448, 9408258048, 2147483648, 21474836480, 35622912,32212254720],
    };
    var width = 460,
        height = 300,
        radius = Math.min(width, height) / 2;
    var color = d3.scale.ordinal()
        .range(["#2DA7E2"]);
    var pie = d3.layout.pie()
        .sort(null);
    var arc = d3.svg.arc()
        .innerRadius(radius - 100)
        .outerRadius(radius - 70);
    var svg = d3.select("body").append("svg")
        .attr("width", width)
        .attr("height", height)
        .append("g")
        .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
    var path = svg.selectAll("path")
        .data(pie(dataset.hddrives))
          .enter().append("path")
         .attr("class", "arc")
        .attr("fill", function(d, i) { return color(i); })
        .attr("d", arc);
    svg.append("text")
          .attr("dy", ".35em")
          .style("text-anchor", "middle")
          .attr("class", "inside")
          .text(function(d) { return 'Test'; });


    }

您的函数donutChart<svg>附加到正文中,而不是在工具提示中。

一个解决方案可以写在你的.html():

.html("<h1>My Donut Chart</h1><br><svg class='myDonut'></svg>")

然后在这行之后调用您的donutChart,记住更改您的var svg:

var svg = d3.select(".myDonut")

注意不要重复相同的变量名,即使它们在函数内(单独的作用域)…这会造成不必要的混淆。