Pie Chart D3js
HTML
<script src="http://labratrevenge.com/d3-tip/javascripts/d3.tip.v0.6.3.js"></script>
<div id="vis" width="300" height="300"></div>
<g id="labels" />
CSS
/* d3 tip */
.d3-tip {
line-height: 1;
font-weight: bold;
padding: 12px;
background: rgba(0, 0, 0, 0.8);
color: #fff;
border-radius: 2px;
}
/* Creates a small triangle extender for the tooltip */
.d3-tip:after {
box-sizing: border-box;
display: inline;
font-size: 10px;
width: 100%;
line-height: 1;
color: rgba(0, 0, 0, 0.8);
content: "\25BC";
position: absolute;
text-align: center;
}
/* Style northward tooltips differently */
.d3-tip.n:after {
margin: -1px 0 0 0;
top: 100%;
left: 0;
}
.d3-tip {
font-size: 13px;
font-family: Consolas;
}
JavaScript
//Width and height
var width = 300;
var height = 300;
r = Math.min(width, height) / 2;
var padding = {
top: 30,
right: 30,
left: 30,
bottom: 30
};
const showLegend = true;
var values = [50, 10, 40];
const radius =
Math.min(width - padding.left - padding.right, height - padding.top - padding.bottom) / 2;
const color = d3.scaleOrdinal().range(colors);
const arc = d3
.arc()
.outerRadius(radius - 10)
.innerRadius(0);
const pie = d3
.pie()
.sort(null)
.value((d) => d);
const div = document.createElement('div');
const svg = d3
.select(div)
.append('svg')
.attr('xmlns', 'http://www.w3.org/2000/svg')
.attr('width', width)
.attr('height', height);
const g = svg
.append('g')
.attr('transform', `translate(${width / 2},${height / 2 + padding.top})`)
.selectAll('.arc')
.data(pie(values))
.enter()
.append('g')
.attr('class', 'arc');
g.append('path')
.attr('d', arc)
.style('fill', (d, i) => color(i));
const requiredHeight = height + (showLegend ? this.styles.legend.fontSize : 0);
this.forceAddPageIfNotFitIn(requiredHeight);
this.doc.addSVG(div.innerHTML, (this.doc.page.width - width) / 2, this.doc.y, {
width,
height,
preserveAspectRatio: 'xMinYMin',
fontCallback: (family: string, bold: boolean, italic: boolean, fontOptions: {}) => 'default',
});
this.doc.y += height;
this.setStyleDefault();
if (!showLegend) {
return;
}
this.addLegend(labels, colors);