Have you tried Flywheel? Learn moreJoin the best designers and creative agencies in the world. Learn more

×
How to add charts to your WordPress site using D3.js

How to add charts to your WordPress site using D3.js

You may be familiar with the term “data visualization,” as it has become more mainstream as both a practice and career path. There’s a reason why this emerging field is well underway – it’s important that we are constantly learning more about our users, as well as showing them the data to back up our claims.

When data is presented in a clean and professional way, it makes it easy to understand and interpret. In most cases, your users are visual people, so what better way to illustrate data than with charts? D3.js, also referred to as Data-Driven Documents, is a great way to add charts to your WordPress site.

wordpress-charts-with-d3-D3-site

Why D3?

This library helps designers showcase data on the web. The possibilities are endless, making this a very popular library. From simple to complex to anything in between, D3 can be customized to render pretty much any type of chart. It plays nicely with standard web technologies, can manipulate the DOM, is super flexible, and the charts can be customized exactly to your liking.

By now, you’ve most likely encountered Scalable Vector Graphics, often referred to as SVGs. This is the type of format that the D3 library creates. SVGs are great because they are small in size, scalable, and resolution independent.

Just to be clear, this solution doesn’t ship with any pre-built charts out of the box – you’ll have to come up with your own! Take a look at the D3 gallery and you can see many great examples to inspire you.

As an Open Source solution, you do not have to worry about licensing and cost. Because it is Open Source, development is ongoing. To keep up to date with the latest version, you can fork D3 on Github.

Making a simple D3 chart

Now that we know how great D3 is, let’s build something. We’ll make a simple donut chart, which will cover the basic concepts of D3.

wordpress-charts-with-d3-donut-chart Here is what the finished chart will look like!

Step one: add the scripts to your site

First, you will need to add the D3 script to your WordPress site. The d3 website has it available for download or you can link directly to the latest version. You will notice that I’m using minified version for this tutorial. D3 is naturally pretty small in size, but the minified is still slightly smaller at only 148 KB.

wordpress-charts-with-d3-d3-minified

Next, you’ll make a new JavaScript file where the custom chart script goes. Give the file a recognizable name so it will be easy to find.

wordpress-charts-with-d3-charts-file

It is very important that the D3 script is called before the chart-specific JavaScript. If things are not called in the right order, the charts will not render. (I know this from personal experience, and if you don’t catch it right away, you’ll likely spend a lot of time trying to fix things that aren’t broken.)

These scripts should be added to your site after the closing body tag. When inspecting the page, make sure that it looks something like this:

<script type="text/javascript" src="js/d3/d3.min.js"></script>
<script type="text/javascript" src="js/charts/charts.js"></script>

Keep in mind that your file path might be different than this, depending on your file structure.

Not sure how to add JavaScript? Learn how to add JavaScript to your site.

Step two: add scripts to create the chart

You will not be touching the d3.js file at all, only working in your specific chart file. In this case, it is called charts.js.

Let’s break things down piece by piece. First, create your variable and establish what you will need in your function. I’ll name this variable donut.

var donut = (function(one) {
})();

Inside the curly braces, you will add your sizing information.

var width = 400,

height = 400,

radius = 200

Next, define your colors. How about a gray and blue chart? The first color listed here is a light grey which will be the default color. The second is the blue color that will represent the data.

colors = d3.scale.ordinal()

.range(['#e8e8e8', '#1dafd3']);

You will need some data to test this with, so let’s add that next. For this tutorial, the data is hardcoded in, but you can also use spreadsheet data and dynamic data with D3.

var piedata = [{

value: 50

}, {

value: 30

}, ]

Now you can add more details that help define how the chart is rendered.

The arc defines the inner radius. Picture the outer radius of the chart – you’ll want it to be fairly thick, so subtracting 100 should be sufficient.

var arc = d3.svg.arc()

.innerRadius(radius - 100)

.outerRadius(radius)

This creates the SVG container and the #donut is what you will be targeting on your page to actually render the chart. This is where you will start to see your colors from the above step.

var donutChart = d3.select('#donut').append('svg')

.attr('width', width)

.attr('height', height)

.append('g')

.attr('transform', 'translate(' + (width - radius) + ',' + (height - radius) + ')')

.selectAll('path').data(pie(piedata))

.enter().append('g')

.attr('class', 'slice')
var slices1 = d3.selectAll('g.slice')

.append('path')

.attr('fill', function(d, range) {

return colors(range);

})

.attr('d', arc)

Finished code

Just in case you want to compare what you have to the sample, here is the complete code snippet.

/* start donut charts */
var donut = (function(one) {
var width = 400,

height = 400,

radius = 200
colors = d3.scale.ordinal()

.range(['#e8e8e8', '#1dafd3']);
var piedata = [{

label: "One",

value: 50

}, {

label: "Two",

value: 30

}, ]
var pie = d3.layout.pie()

.value(function(d) {

return d.value;

})
var arc = d3.svg.arc()

.innerRadius(radius - 100)

.outerRadius(radius)
var donutChart = d3.select('#donut').append('svg')

.attr('width', width)

.attr('height', height)

.append('g')

.attr('transform', 'translate(' + (width - radius) + ',' + (height - radius) + ')')

.selectAll('path').data(pie(piedata))

.enter().append('g')

.attr('class', 'slice')
var slices1 = d3.selectAll('g.slice')

.append('path')

.attr('fill', function(d, range) {

return colors(range);

})

.attr('d', arc)

})();

Seeing the chart

You will need to create a new page or post so you can “call” the donut chart to actually see it. Make sure that you are in Text edit mode.

 <div>

      <svg id="donut" viewBox="0 0 400 400" perserveAspectRatio="xMinYMid"></svg>

</div>

Viewbox and aspect ratio to size chart

There is something extra in the SVG tag, which is the viewBox and preserveAspectRatio. This was not generated by D3, and is totally optional. You may have another preferred method of sizing, but this tends to work well, and it helps with the responsiveness of the charts.

Especially in this case, being that we want to keep a perfectly round shape, setting an aspect ratio will ensure that the SVG scales to fit. This is where the viewBox comes into play. The advantage to the viewBox is that it defines how all the measurements and coordinates used inside the SVG should be scaled to fit in the available space. If you are also using 400 as a measurement, here’s a quick explanation as to how to keep the circular shape.

We have two values of 400 that are the same; the reason for this is so the image scales properly. With our viewBox="0 0 400 400", we are creating a coordinate system for the graphic. It is 400 units wide and 400 units high. The width and height of the SVG graphic establishes the visible area and setting a viewBox allows you to specify that your graphics can stretch to fit a certain container (most likely the viewport by default, which is the part of the web page that the user can currently see).

There’s a little more to it because even with the viewBox defined, it still won’t scale perfectly. It won’t be distorted, which is a good thing, but there is more to the equation. Meet the wingman, preserveAspectRatio. It has no effect unless there is a viewBox that defines the aspect ratio of the image. The scale will be adjusted in order to preserve the aspect ratio, so you can keep your perfectly circular chart. When including the preserveAspectRatio, you are planning for instances when the viewBox does not match the aspect ratio of the viewport or container that the chart is in. In most cases, by default, the image will scale until it fits both the height and width but centers itself within any extra space. We’ve included preserveAspectRatio="xMidYMid" which is telling the browser to center the graphic within the viewport in both directions.

wordpress-charts-with-d3-donut-chart

The most important takeaway is knowing that the graphic will not get cut off and that it is scalable. The key to really understanding this is to experiment with the values. A good way to do that is to see what happens when the values are changed and how it relates to the viewport.

Browser support and d3

Chances are that you are using a modern browser, but it is worth mentioning if you have to support older browsers. Overall, browser support is great, and you probably won’t run into any issues, but D3.js doesn’t work well with older browsers like IE8.

Creating a simple chart is a great way to be up and running with D3.js. Knowing the basics, and becoming familiar with D3 starter charts will be very helpful to you as you design your data and move onto more chart types. From simple to complex, the design options are infinite.

How’d your chart turn out? Let us know in the comments?

Join the discussion

Share this article:
Get more great content in your inbox

More articles

Get content like this sent directly to your inbox!

Install WordPress locally free