Oh boy, it’s been over a year since I last posted. Too much learning, and trying to keep my head above water with all that’s new in the javascript eco-system.
Anyway here is a very simple pie chart as a react component using SVG. If you don’t want to install a huge JS library just to get a simple pie chart, maybe just copy and paste this code.
It is based heavily on David Gilbertson wonderfully written A simple pie chart in SVG.
You use it as you would any other react component. There are two properties you pass in: its size (ie. radius) and an object which contains an array of the slices, which describe the percent and color.
1 2 3 4 5 6 7 |
let slices = [ {percent: 0.1, color: '#c1d138'}, {percent: 0.7, color: '#7e97db'}, {percent: 0.2, color: '#00ab6b'} ] component = <PieChart slices={slices} width={150}/> |
Here is the code (note: in JSX and ES6):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
import React from "react"; export default class PieChart extends React.Component{ constructor(props) { super(props) } render() { let viewBox=` -${this.props.width} -${this.props.width} ${this.props.width*2} ${this.props.width*2}` let transform = "rotate(0 0 0)"; //if you want it rotated a certain angle change the first number in the this transform object return ( <div> <div> <svg width={this.props.width} height={this.props.width} viewBox={viewBox} transform = {transform}> {getPaths(this.props.slices, this.props.width)} </svg> </div> </div> ); } } function getCoordinatesForPercent(percent) { const x = Math.cos(2 * Math.PI * percent); const y = Math.sin(2 * Math.PI * percent); return [x, y]; } let cumulativePercent = 0; const getPaths = (slices, size) => { let paths = []; slices.forEach(slice => { let [startX, startY] = getCoordinatesForPercent(cumulativePercent); cumulativePercent += slice.percent; const [endX, endY] = getCoordinatesForPercent(cumulativePercent); // if the slice is more than 50%, take the large arc (the long way around) const largeArcFlag = slice.percent > .5 ? 1 : 0; // create an array and join it just for code readability const pathData = [ `M ${startX * size} ${startY * size}`, // Move `A ${size} ${size} 0 ${largeArcFlag} 1 ${endX * size} ${endY * size}`, // Arc (size is same as radius) `L 0 0`, // Line ].join(' '); paths.push(<path d={pathData} fill={slice.color}/>) }); return paths; } |