2016-06-24 33 views
1

我正在嘗試在工具提示中顯示圓環圖。我認爲這只是簡單地在.html()中添加函數名稱或創建圖表,但事實並非如此。誰能告訴我我哪裏出錯了?D3在工具提示中添加圓環圖

這裏是我的代碼:

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'; }); 




    } 

回答

1

你的功能donutChart追加<svg>的身體,而不是工具提示中。

一個解決方案可以在你的.html()寫這篇:

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

然後打電話給你的donutChart該行後,記得要改變你的var svg

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

小心不重複相同變量名稱,即使它們在函數內部(單獨的作用域)......它可能會導致不必要的混淆。