Skip to content

Instantly share code, notes, and snippets.

@thomaswilburn
Created July 7, 2019 19:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomaswilburn/475a2c7c2e101d79b19b0c85c55c5754 to your computer and use it in GitHub Desktop.
Save thomaswilburn/475a2c7c2e101d79b19b0c85c55c5754 to your computer and use it in GitHub Desktop.
Demo of making a D3 chart
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello!</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
This space intentionally left blank. Test
<div class="container">
<svg class="graph"></svg>
</div>
<script src="https://unpkg.com/d3"></script>
<script>
var svg = d3.select(".graph");
svg.attr("width", 120)
.attr("height", 100);
var data = [1, 2, 3];
//margin pattern: https://bl.ocks.org/mbostock/3019563
var chartSize = {
x: 30,
y: 10,
width: 70,
height: 70
};
//https://www.d3indepth.com/scales/
var xScale = d3.scaleLinear()
.domain([0, data.length])
.range([0, chartSize.width]);
var min = Math.min(...data);
var max = Math.max(...data);
if (min > 0) min = 0;
var yScale = d3.scaleLinear()
.domain([min, max])
.range([chartSize.height, 0]);
var xAxis = d3.axisBottom()
.scale(xScale)
.ticks(4);
var yAxis = d3.axisLeft()
.ticks(5)
// .tickFormat(d => d)
.scale(yScale);
svg
.append("g")
.attr("transform", `translate(${chartSize.x}, ${chartSize.y + chartSize.height})`)
.call(xAxis);
svg
.append("g")
.attr("transform", `translate(${chartSize.x}, ${chartSize.y})`)
.call(yAxis);
//enter-exit:https://medium.com/@c_behrens/enter-update-exit-6cafc6014c36
svg.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("x", (_, i) => chartSize.x + xScale(i) + 1)
.attr("y", d => chartSize.y + yScale(d))
.attr("height", d => chartSize.height - yScale(d))
.attr("width", xScale(1) - 2);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment