Source

46 chart lines · 1 file · 1.4 kBBenchmark harness excluded · shared/mount.ts

1983 ASA automobile data406 records · CSV · 17.4 kB
@charts-poc/demo-data/cars

Selection: Complete published snapshot

name
string
economy (mpg)
number | null
cylinders
number
displacement (cc)
number
power (hp)
number | null
weight (lb)
number
0-60 mph (s)
number
year
number

1983 ASA Data Exposition@observablehq/sample-datasets@1.0.1 · revision 732c0148de74 · cars.csv · ISC distribution; upstream source credited · SHA-256 eaad8395d37ePinned snapshot

cases/histogram/tanstack.ts46 lines · entry
cases/histogram/tanstack.ts
import { cars } from '@charts-poc/demo-data/cars'
import { binX, defineChart, rect } from '@tanstack/charts'
import { scaleLinear } from 'd3-scale'
import { tanstackMount } from '../../shared/mount'
import type { CarsRow } from '@charts-poc/demo-data/cars'
import type { ConformanceInput } from '../../types'

type CarWithEconomy = CarsRow & { 'economy (mpg)': number }

const completeCars = cars.filter(
  (row): row is CarWithEconomy => row['economy (mpg)'] !== null,
)
const boundaries = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
const definition = (input: ConformanceInput) => {
  const bins = binX(completeCars.slice(input.revision * 8), {
    value: 'economy (mpg)',
    thresholds: boundaries,
    outputs: { count: { reduce: 'count' } },
  })

  return defineChart({
    marks: [
      rect(bins, {
        x1: 'x1',
        x2: 'x2',
        y1: () => 0,
        y2: 'count',
        fill: '#2563eb',
        inset: 1,
      }),
    ],
    x: {
      scale: scaleLinear,
      grid: true,
      axis: { label: 'Fuel economy (mpg)' },
    },
    y: { scale: scaleLinear, grid: true, axis: { label: 'Count' } },
  })
}

export const mount = tanstackMount(definition, 'Histogram of fuel economy', {
  format: ({ datum }) =>
    `${datum.x1.toLocaleString('en-US')}${datum.x2.toLocaleString(
      'en-US',
    )} · ${datum.count.toLocaleString('en-US')} observations`,
})