Skip to content

Instantly share code, notes, and snippets.

@davegotz
Last active January 12, 2022 01:58
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 davegotz/2c9f6e5efc6425290500c7dc0be56703 to your computer and use it in GitHub Desktop.
Save davegotz/2c9f6e5efc6425290500c7dc0be56703 to your computer and use it in GitHub Desktop.
Basic Line Chart
<html>
<head>
<title>Basic Line Chart</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;
let data = [
[0, 0.1],
[10, 0.4],
[20, 0.2],
[30, 0.3],
[40, 0.2],
[50, 0.5],
[60, 0.2],
[70, 0.9],
[80, 0.4],
[90, 0.3],
[100, 0.1],
];
// 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");
// Add the line for the line chart.
let line = d3.line()
.x(d => x(d[0]))
.y(d => y(d[1]));
svg.append("path")
.attr("d", line(data))
.attr("fill", "none")
.attr("stroke", "black");
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment