Skip to content

Instantly share code, notes, and snippets.

@Vintharas

Vintharas/.block

Last active Aug 22, 2019
Embed
What would you like to do?
Simple example scales
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v5.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
svg {background: #EEE;}
</style>
<svg width=900 height=500></svg>
</head>
<body>
<script>
const cookiesThisWeek = [10, 20, 10, 50, 1, 12, 2];
const svg = d3.select("svg");
const width = +svg.attr('width');
const height = +svg.attr('height');
const yScale = d3.scaleLinear()
.domain([d3.min(cookiesThisWeek), d3.max(cookiesThisWeek)])
.range([0, height]);
const daysOfTheWeek = [...cookiesThisWeek.keys()]
const xScale = d3.scaleBand()
.domain(daysOfTheWeek)
.range([0, width])
.padding(0.1);
const colorScale = d3.scaleOrdinal(d3.schemeBlues[7])
svg
.selectAll("rect")
.data(cookiesThisWeek)
.enter()
.append('rect')
.attr('x', (_, i) => xScale(i))
.attr('y', (d) => height - yScale(d))
.attr('width', xScale.bandwidth())
.attr('height', (d) => yScale(d))
.attr('fill', (_,i) => colorScale(i))
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment