Public
Edited
Apr 25, 2023
1 fork
Importers
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
tanahu_population_2068_barchart =
barChart(popByAgeGroup2068, {
x: "year",
y: "population",

yLabel: "↑ Population",
xLabel: "Year (Nepali)"
})
Insert cell
popByAgeGroup2068 = popByYear.filter((d) => d.gender === "all")
Insert cell
Insert cell
tanahu_populatoin_ratio_male_female_2068_barchart =
barChart(popByGender, {
x: "gender",
y: "population",
grouping: "year",
sort: 'y',
reverse: true,

yLabel: "↑ Population"
})
Insert cell
popByGender = popByYear.filter(d => d.gender !== "all")
Insert cell
Insert cell
function barChart(
data,
{
// Required
x = "x", // The key or accessor function for variants along x-axis
y = "y", // The key or accessor function for variants along y-axis
grouping, // The key or accessor function for variants based which faciting is done

// Optional
sort, // Sort the bar by values on axis. Supports 'x' or 'y'.
reverse = false, // Reverses sort

width,
height,

yLabel,
yTickFormat = "s",

xLabel,
xTickFormat,

groupingLabel = null, // Label when grouping/faceting. null to hide the default label

fill,
scheme = schemeCategory10
} = {}
) {
const xAccessor = typeof x === "function" ? x : (d) => d[x];
const yAccessor = typeof y === "function" ? y : (d) => d[y];
const gAccessor =
typeof grouping === "function"
? grouping
: typeof grouping == "string"
? (d) => d[y]
: grouping;

const sortAccessor = sort === "y" ? xAccessor : xAccessor;
let domain = [...new Set(data.map(sortAccessor))];
if (sort) {
domain = [...new Set(d3.sort(data, sortAccessor).map(xAccessor))];
}

if (reverse) {
domain = domain.slice().reverse();
}

if (grouping == null) {
return Plot.plot({
width,
height,

x: { type: "band", domain, label: xLabel, tickFormat: xTickFormat },
y: { grid: true, label: yLabel, tickFormat: yTickFormat },

marks: [
Plot.ruleY([0]),
Plot.barY(data, {
x: xAccessor,
y: yAccessor,
fill: fill || scheme[0] || main.blue["700"],
title: xAccessor
})
]
});
}

const groups = [...new Set(data.map((d) => d[grouping]))];

// Based on https://observablehq.com/@observablehq/plot-bar?collection=@observablehq/plot#cell-1005
return Plot.plot({
padding: 0.01,
width,
height,
color: { domain, range: scheme, legend: true },
x: {
domain,
axis: null,
tickFormat: xTickFormat
},
y: { grid: true, label: yLabel, tickFormat: yTickFormat },
fx: {
label: groupingLabel,
domain: groups,
padding: 0.1
},
facet: { data, x: grouping },

marks: [
Plot.ruleY([0]),
Plot.barY(data, {
x: xAccessor,
y: yAccessor,
fill: xAccessor
})
]
});
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
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