我正在开始学习使用d3.js可视化数据的过程,到目前为止,我发现Scott Murray的“交互式数据可视化”非常有用.我正在阅读第11章中的一些示例代码,并想知道如何将工具提示添加到饼图(本书已经使用条形图描述了此过程).无论如何,只是在过去几个小时内修补了代码,并想看看是否有人可以借此给我:
<!DOCTYPE html> <html lang="en"> <head> <@R_502_338@ charset="utf-8"> <title>D3: Pie layout</title> <script type="text/javascript" src="d3/d3.v3.js"></script> <style type="text/css"> text { font-family: sans-serif; font-size: 12px; fill: white; } #tooltip { position: absolute; width: 200px; height: auto; padding: 10px; background-color: white; -webkit-border-radius: 10px; -moz-border-radius: 10px; border-radius: 10px; -webkit-Box-shadow: 4px 4px 10px rgba(0,0.4); -mox-Box-shadow: 4px 4px 4px 10px rgba(0,0.4); Box-shadow: 4px 4px 10px rbga(0,0.4) pointer-events: none; } #tooltip.hidden { display: none; } #tooltip p { margin: 0; font-family: sans-serif; font-size: 16px; line-height: 20px; } </style> </head> <body> <div id="tooltip" class="hidden"> <p><strong>Important Label Heading</strong></p> <p><span id="value">100</span>%</p> </div> <script type="text/javascript"> //Width and height var w = 300; var h = 300; var dataset = [ 5,10,20,45,6,25 ]; var outerRadius = w / 2; var innerRadius = 0; var arc = d3.svg.arc() .innerRadius(innerRadius) .outerRadius(outerRadius); var pie = d3.layout.pie(); // Easy colors accessible via a 10-step ordinal scale var color = d3.scale.category10(); // Create SVG element var svg = d3.select("body") .append("svg") .attr("width",w) .attr("height",h); // Set up groups var arcs = svg.selectAll("g.arc") .data(pie(dataset)) .enter() .append("g") .attr("class","arc") .attr("transform","translate(" + outerRadius + "," + outerRadius + ")") .on("mouSEOver",function(d){ d3.select("#tooltip") .select("#value") .text(d); d3.select("tooltip").classed("hidden",false); }) .on("mouSEOut",function() { // Hide the tooltip d3.select("#tooltip").classed("hidden",true); }); // Draw arc paths arcs.append("path") .attr("fill",function(d,i) { return color(i); }) .attr("d",arc); // Labels arcs.append("text") .attr("transform",function(d) { return "translate(" + arc.centroid(d) + ")"; }) .attr("text-anchor","middle") .text(function(d) { return d.value; }); </script> </body> </html>
我知道这有点消化,但我更想知道的是如何设置工具提示的x和y值.先感谢您.