Skip to content

Instantly share code, notes, and snippets.

@girish1729
Last active April 20, 2024 03:40
Show Gist options
  • Save girish1729/b3eaaa1cdbc0026a3d1cab3236dd5e61 to your computer and use it in GitHub Desktop.
Save girish1729/b3eaaa1cdbc0026a3d1cab3236dd5e61 to your computer and use it in GitHub Desktop.
<script>
import { scaleLinear } from 'd3-scale';
const points = [
{ year: 2000, birthrate: 16.7 },
{ year: 2005, birthrate: 14.6 },
{ year: 2010, birthrate: 14.4 },
{ year: 2015, birthrate: 14 },
{ year: 2020, birthrate: 13 },
{ year: 2025, birthrate: 12.4 }
];
const xTicks = [2000, 2005, 2010, 2015, 2020, 2025];
const yTicks = [0, 5, 10, 15, 20];
const padding = { top: 20, right: 15, bottom: 20, left: 25 };
let width = 500;
let height = 200;
function formatMobile(tick) {
return "'" + tick.toString().slice(-2);
}
$: xScale = scaleLinear()
.domain([0, xTicks.length])
.range([padding.left, width - padding.right]);
$: yScale = scaleLinear()
.domain([0, Math.max.apply(null, yTicks)])
.range([height - padding.bottom, padding.top]);
$: innerWidth = width - (padding.left + padding.right);
$: barWidth = innerWidth / xTicks.length;
</script>
<h2>US birthrate by year (sample data)</h2>
<div class="chart" bind:clientWidth={width} bind:clientHeight={height}>
<svg>
<!-- y axis -->
<g class="axis y-axis">
{#each yTicks as tick}
<g class="tick tick-{tick}"
transform="translate(0, {yScale(tick)})">
<line x2="100%" />
<text y="-4">{tick} {tick === 20
? ' per 1,000 population' : ''}</text>
</g>
{/each}
</g>
<!-- x axis -->
<g class="axis x-axis">
{#each points as point, i}
<g class="tick"
transform="translate({xScale(i)},{height})">
<text x={barWidth / 2}
y="-4">{width > 380 ? point.year : formatMobile(point.year)}</text>
</g>
{/each}
</g>
<g class="bars">
{#each points as point, i}
<rect
x={xScale(i) + 2}
y={yScale(point.birthrate)}
width={barWidth - 4}
height={yScale(0) -
yScale(point.birthrate)}
/>
{/each}
</g>
</svg>
</div>
<style>
h2 {
text-align: center;
}
.chart {
width: 100%;
max-width: 500px;
margin: 0 auto;
}
svg {
position: relative;
width: 100%;
height: 500px;
}
.tick {
font-family: Helvetica, Arial;
font-size: 0.725em;
font-weight: 200;
}
.tick line {
stroke: #e2e2e2;
stroke-dasharray: 2;
}
.tick text {
text-anchor: start;
font-weight: 56px;
}
.tick.tick-0 line {
stroke-dasharray: 0;
}
.x-axis .tick text {
text-anchor: middle;
}
.bars rect {
fill: red;
stroke: none;
opacity: 1;
}
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment