|
<!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; } |
|
</style> |
|
<svg width=900 height=500></svg> |
|
</head> |
|
|
|
<body> |
|
<script> |
|
const cookiesThisWeek = [ |
|
{day: 'Monday', cookies: 10}, |
|
{day: 'Tuesday', cookies: 20}, |
|
{day: 'Wednesday', cookies: 10}, |
|
{day: 'Thursday', cookies: 61}, |
|
{day: 'Friday', cookies: 1}, |
|
{day: 'Saturday', cookies: 12}, |
|
{day: 'Sunday', cookies: 2}]; |
|
|
|
const svg = d3.select("svg"); |
|
|
|
const width = +svg.attr('width'); |
|
const height = +svg.attr('height'); |
|
const margin = 40; |
|
const innerHeight = height - 2*margin; |
|
const innerWidth = width - 2*margin; |
|
|
|
|
|
const yScale = d3.scaleLinear() |
|
.domain([d3.min(cookiesThisWeek.map(c => c.cookies)), d3.max(cookiesThisWeek.map(c => c.cookies))]) |
|
.range([height - 2*margin, 0]); |
|
|
|
|
|
const daysOfTheWeek = cookiesThisWeek.map(c => c.day) |
|
const xScale = d3.scaleBand() |
|
.domain(daysOfTheWeek) |
|
.range([0, width - 2*margin]) |
|
.padding(0.1); |
|
|
|
const colorScale = d3.scaleOrdinal(d3.schemeBlues[7]) |
|
|
|
const g = svg.append('g') |
|
.attr('transform', `translate(${margin}, ${margin})`); |
|
|
|
g.append('g').call(d3.axisLeft(yScale)); |
|
g.append('g') |
|
.attr('transform', `translate(0, ${innerHeight})`) |
|
.call(d3.axisBottom(xScale)); |
|
|
|
g |
|
.selectAll("rect") |
|
.data(cookiesThisWeek) |
|
.enter() |
|
.append('rect') |
|
.attr('x', (d) => xScale(d.day)) |
|
.attr('y', (d) => yScale(d.cookies)) |
|
.attr('width', xScale.bandwidth()) |
|
.attr('height', (d) => innerHeight - yScale(d.cookies)) |
|
.attr('fill', (_,i) => colorScale(i)); |
|
|
|
|
|
|
|
</script> |
|
</body> |