Published
Edited
Sep 30, 2021
Insert cell
Insert cell
Insert cell
fruits = [
{name: "🍊", count: 21},
{name: "🍇", count: 13},
{name: "🍏", count: 8},
{name: "🍌", count: 5},
{name: "🍐", count: 3},
{name: "🍋", count: 2},
{name: "🍎", count: 1},
{name: "🍉", count: 1}
]
Insert cell
fruits.map(d => d.count) // the count dimension (quantitative)
Insert cell
fruits.map(d => d.name) // the name dimension (nominal)
Insert cell
Insert cell
Insert cell
x = d3.scaleLinear()
.domain([0, d3.max(fruits, d => d.count)])
.range([margin.left, width - margin.right])
Insert cell
y = d3.scaleBand()
.domain(fruits.map(d => d.name))
.range([margin.top, height - margin.bottom])
.padding(0.2)
Insert cell
Insert cell
x.domain()
Insert cell
x.range()
Insert cell
y("🍊") // the y-coordinate for name = grapes
Insert cell
x(13) // the x-coordinate corresponding to count = 21
Insert cell
x(0) // the x-coordinate corresponding to count = 0
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
x(21) - x(0) // the width of the bar corresponding to count = 21
Insert cell
y.bandwidth() // the height of each bar
Insert cell
Insert cell
Insert cell
html`<svg viewBox="0 0 ${width} 33" style="max-width: ${width}px; font: 10px sans-serif; display: block;">
<rect fill="steelblue" x="${x(0)}" width="${x(count) - x(0)}" height="33"></rect>
<text fill="white" text-anchor="end" x="${x(count)}" dx="-6" dy="21">${count}</text>
</svg>`
Insert cell
Insert cell
html`<svg viewBox="0 ${margin.top} ${width} ${height - margin.top}" style="max-width: ${width}px; font: 10px sans-serif;">
${fruits.map(d => svg`<rect y="${y(d.name)}" x="${x(0)}" width="${x(d.count) - x(0)}" height="${y.bandwidth()}"></rect>`)}
</svg>`
Insert cell
Insert cell
fruits
Insert cell
Insert cell
md `
---

<h3 style="text-align: right">
[Axes →](https://observablehq.com/@parshwamehta13/axes)
</h3>
`
Insert cell
Insert cell
width = 640
Insert cell
height = 202
Insert cell
margin = ({top: 20, right: 20, bottom: 20, left: 20})
Insert cell
import {legend} from "@d3/color-legend"
Insert cell
d3 = require("d3@6")
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