How to Use D3.js in a Hugo Blog Post

Hongtao Hao / 2021-05-17


It’s in fact very easy to use D3.js in a Hugo blog post.

First, we need to insert the link to the latest release of D3 :

<script src="https://d3js.org/d3.v6.min.js"></script>

Put the above code anywhere in your blog post.

Then, we can create a div to contain the visualization:

<div id="div">
</div>

Put the above codes in the place where you want to insert the visualization.

Last, simply use D3.js. For example,

<script>
   const svg = d3.select("#div")
                 .append("svg")
                 .attr("width", "550")
                 .attr("height", "100")
                 .style("background-color", "lightblue")
                 .attr("id", "demo1")

   let rect = d3.select("#demo1")
	            .append("rect")
	            .attr("x", "200")
	            .attr("y", "20")
	            .attr("width", "100")
	            .attr("height", "70")
	            .attr("fill", "orange")
                .attr("stroke", "blue")
                .attr("stroke-width", "3px")
</script>

We can also use CSS to style the visualization. For example, we can center it with:

<style type="text/css">
	#div {
		text-align: center
	}
</style>

This is just a very simple example. Of course, you can use very complicated D3.js codes in a post.

Things worth mentioning #

First, if you are a heavy D3 user. You can put <script src="https://d3js.org/d3.v6.min.js"></script> within <head>, which normally is found within layouts/partials/header.html. This might vary based on the themes you are using, of course.

Second, even if you have multiple <script></script> blocks, keep in mind that the whole post should be viewed as a single JavaScript file. This means you can directly reference variables declared in previous <script></script> blocks.

For example, since we already have const svg = above, add svg.style('border-style', 'dotted')

<script>
	svg.style('border-style', 'dotted')
</script>

will change the above visualization to:

Third, you have to declare a variable before you can reference it. This holds true outside of Hugo as well, for example, when you are creating a D3 data visualization in a basic HTML file.

Last modified on 2021-10-05