Skip to content

Instantly share code, notes, and snippets.

@davegotz
Created January 20, 2022 02:27
Show Gist options
  • Save davegotz/bc5faf37be4a31e49575d394e9f4b611 to your computer and use it in GitHub Desktop.
Save davegotz/bc5faf37be4a31e49575d394e9f4b611 to your computer and use it in GitHub Desktop.
Let's Make a Bar Chart with SVG
<html>
<body>
<script src="https://d3js.org/d3.v7.min.js"></script>
<svg class="chart" height="300" width="500">
</svg>
<script>
// This is the data array which will be represented as a bar chart.
let data = [4, 8, 15, 16, 23, 42];
// Define an x and y scale.
let x = d3.scaleLinear()
.domain([0, data.length])
.range([0, 500]);
let y = d3.scaleLinear()
.domain([0, d3.max(data)])
.range([300, 0]);
// Select the chart svg which will be the container for the new bar chart
let chart = d3.select(".chart");
// Define some layout parameters.
let text_spacing = 4;
let bar_spacing = 2;
let bar_width = x(1) - x(0) - bar_spacing;
// Perform the data join and add the new rectangles
chart.selectAll("rect")
.data(data).join("rect")
.style("fill", "steelblue")
.attr("x", (d,i) => x(i))
.attr("y", d => y(d))
.attr("height", d => 300-y(d))
.attr("width", bar_width);
// Perform the data join again, this time to create the text labels to show the data values.
chart.selectAll("text")
.data(data).join("text")
.style("fill", "white")
.style("font-family", "sans-serif")
.style("font-size", "16pt")
.style("text-anchor", "middle")
.style("dominant-baseline", "hanging")
.attr("x", (d,i) => x(i) + 0.5*bar_width)
.attr("y", d => y(d)+text_spacing)
.text(d => d);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment