Published
Edited
Sep 29, 2020
Importers
2 stars
Insert cell
md`# Person Diagram`
Insert cell
drawPersonDiagram(
[
{
label: 'Female',
value: 10774923,
iconID: 'woman',
color: 'pink',
width: 100,
height: 100
},
{
label: 'Male',
value: 10493482,
iconID: 'man',
color: 'blue',
width: 32,
height: 32
}
],
{ caption: 'Sri Lanka Demographics by Gender' }
)
Insert cell
d3 = require('d3@6')
Insert cell
import { range } from '@nuuuwan/list-utils'
Insert cell
import { _ } from '@nuuuwan/html-utils'
Insert cell
import { addDefaults } from '@nuuuwan/option-utils'
Insert cell
import { getSVG, drawPath } from '@nuuuwan/svg-utils'
Insert cell
import { drawIcon } from '@nuuuwan/svg-icons'
Insert cell
function drawPersonDiagram(dataList, options) {
options = addDefaults(
options,
Object({
caption: 'No Label',
nIcons: 100,
funcFormatValue: d3.format(','),
iconsPerRow: 20
})
);

const totalValue = dataList.reduce(
(totalValue, d) => totalValue + d.value,
0
);

const [childList, iAll] = dataList.reduce(
function([childList, iAll], d) {
const n = Math.round((d.value * options.nIcons) / totalValue, 0);
return range(0, n).reduce(
function([childList, iAll], i) {
iAll += 1;
let iconOptions = d;
iconOptions = addDefaults(iconOptions, options);
iconOptions = addDefaults(iconOptions, { fill: d.color });

childList.push(drawIcon(d.iconID, iconOptions));
if (iAll % options.iconsPerRow === 0) {
childList.push(_('br'));
}
return [childList, iAll];
},
[childList, iAll]
);
},
[[], 0]
);

const legendChildList = dataList.map(function(d) {
return _('div', [
drawIcon(d.iconID, addDefaults(options, { fill: d.color })),
_('span', `${d.label} (${options.funcFormatValue(d.value)})`)
]);
});

return _(
'figure',
[
_('div', childList),
_('div', legendChildList, { style: { margin: '32px' } }),
_('figcaption', 'Figure: ' + options.caption, {
style: { 'text-align': 'center' }
})
],
{ style: { padding: '32px', 'text-align': 'center' } }
);
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more