Skip to content

Instantly share code, notes, and snippets.

@JustinSHong
Last active April 15, 2019 01:55
Show Gist options
  • Save JustinSHong/be25ac0d62768650c8d745b13b082dc3 to your computer and use it in GitHub Desktop.
Save JustinSHong/be25ac0d62768650c8d745b13b082dc3 to your computer and use it in GitHub Desktop.
Scales and Axes
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
svg {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<svg></svg>
<script>
const data = [100, 250, 175, 200, 120];
const rectHeight = 300;
const rectWidth = 50;
const svg = d3.select('svg');
// determine min and max values from data set
const min = d3.min(data);
const max = d3.max(data);
const extent = d3.extent(data);
console.log("min", min);
console.log("max", max);
console.log("extent", extent);
// define scales
const xScale = d3.scaleLinear().domain([0, data.length]).range([0, rectWidth * data.length]);
const yScale = d3.scaleLinear().domain([min, max]).range([rectHeight, 0]);
// define x-axis
const xAxis = d3.axisBottom().scale(xScale);
// define y-axis
const yAxis = d3.axisLeft().scale(yScale);
// append axes
svg.append('g')
.attr('transform', 'translate(40, 320)')
.call(xAxis);
svg.append('g')
.attr('transform', 'translate(40, 20)')
.call(yAxis);
// creat rectangles for bar chart
svg.selectAll('rect')
.data(data)
.enter()
.append('rect')
.attr('transform', 'translate(40, 20)')
.attr('x', (d, i) => i * rectWidth)
.attr('y', (d, i) => rectHeight - d)
.attr('width', (d, i) => rectWidth)
.attr('height', (d, i) => d)
.attr('fill', 'blue')
.attr('stroke', 'white');
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment