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=""></script>

Put the above code anywhere in your blog post.

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

<div id="div">

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

Last, simply use D3.js. For example,

   const svg ="#div")
                 .attr("width", "550")
                 .attr("height", "100")
                 .style("background-color", "lightblue")
                 .attr("id", "demo1")

   let rect ="#demo1")
	            .attr("x", "200")
	            .attr("y", "20")
	            .attr("width", "100")
	            .attr("height", "70")
	            .attr("fill", "orange")
                .attr("stroke", "blue")
                .attr("stroke-width", "3px")

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

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

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=""></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'border-style', 'dotted')

<script>'border-style', 'dotted')

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