Skip to content

Instantly share code, notes, and snippets.

@stevekinney
Last active October 31, 2016 00:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevekinney/b6467eebfd47df100315b8d3e471f2c5 to your computer and use it in GitHub Desktop.
Save stevekinney/b6467eebfd47df100315b8d3e471f2c5 to your computer and use it in GitHub Desktop.
import React from 'react';
const StackedBarGraph = ({ width, height, colors, children }) => {
const add = (a, b) => a + b;
const values = children.map(dataPoint => dataPoint.props.value);
const sum = values.reduce(add, 0);
const widths = values.map(value => width / sum * value);
const startingPoints = values.map((value, index) => widths.slice(0, index).reduce(add, 0));
const rects = children.map((datapoint, index) => (
<rect
x={startingPoints[index]}
y={0}
width={widths[index]}
height={height}
key={index}
fill={colors[index % colors.length]}
/>
));
return (
<svg width={width} height={height} viewBox={`0 0 ${width} ${height}`} xmlns="http://www.w3.org/2000/svg">
<g>
{rects}
</g>
</svg>
);
}
StackedBarGraph.defaultProps = {
width: 600,
height: 40,
colors: ['#D0011B', '#50E3C2', '#F8E71C', '#4A90E2']
};
StackedBarGraph.propTypes = {
width: React.PropTypes.number.isRequired,
height: React.PropTypes.number.isRequired
};
export default StackedBarGraph;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment