e.g of Pie Chart with Tooltip
by Nivaldo
HTML
<div id="tooltip" class="hidden">
<p><strong>Important Label Heading</strong>
</p>
<p><span id="value">100</span>%</p>
</div>
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, 0, 0.4);
-mox-box-shadow: 4px 4px 4px 10px rgba(0, 0, 0, 0.4);
box-shadow: 4px 4px 10px rbga(0, 0, 0, 0.4) pointer-events: none;
}
#tooltip.hidden {
opacity: 0;
}
#tooltip p {
margin: 0;
font-family: sans-serif;
font-size: 16px;
line-height: 20px;
}
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")
.style("left", d3.event.pageX + "px")
.style("top", d3.event.pageY + "px")
.style("opacity", 1)
.select("#value")
.text(d.value);
})
.on("mouseout", function () {
// Hide the tooltip
d3.select("#tooltip")
.style("opacity", 0);;
});
// 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;
});