Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.