Skip to content

Instantly share code, notes, and snippets.

@davegotz
Last active January 12, 2022 01:59
Show Gist options
  • Save davegotz/bf5ac2f5e0a147afb338adfd2d2b4e96 to your computer and use it in GitHub Desktop.
Save davegotz/bf5ac2f5e0a147afb338adfd2d2b4e96 to your computer and use it in GitHub Desktop.
Simple Example of D3 Axes
<html>
<head>
<title>Simple Example of D3 Axes</title>
<script src="https://d3js.org/d3.v7.min.js"></script>
<style>
/* Style information for axis labels */
.axis-label {
font-family: sans-serif;
font-size: 12px;
}
/* Style information for axis lines and tick marks */
.axis path,
.axis line {
fill: none;
stroke: black;
shape-rendering: crispEdges;
}
.axis text {
font-family: sans-serif;
font-size: 11px;
}
</style>
</head>
<body>
<svg width="640" height="480"></svg>
<script>
let margin = 40;
// Define scales for the x and y axes.
// We'll set the x axis to be 0-100
var x = d3.scaleLinear()
.domain([0,100])
.range([margin,640-margin]);
// And we'll set the y axis to be 0-1
var y = d3.scaleLinear()
.domain([0,1])
.range([480-margin,margin]);
let svg = d3.select("svg");
// New draw the X axis and label.
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(0,"+(480-margin)+")")
.call(d3.axisBottom(x))
svg.append("text")
.attr("class", "axis-label")
.attr("x", x(50))
.attr("y", 480-3)
.style("text-anchor", "middle")
.text("X Axis Label");
// Now the Y axis and label.
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate("+margin+",0)")
.call(d3.axisLeft(y));
svg.append("text")
.attr("transform", "rotate(90)")
.attr("class", "axis-label")
.attr("x", y(0.5))
.attr("y", -3)
.style("text-anchor", "middle")
.text("Y Axis Label");
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment