Raspberry Pi Pico Tips and Tricks

Tuesday 1 January 2013

Adding a title to your d3.js graph

The following post is a portion of the D3 Tips and Tricks document which it free to download from the main page. To use this post in context, consider it with the others in the blog or just download the pdf :-)

If you've read through the adding the axis labels section most of this will come as no surprise.

What we want to do to add a title to the graph is to add a text element (just a few words) that will appear above the graph and centred left to right.

The code block we will use will looks like this;
        .attr("x", (width / 2))             
        .attr("y", 0 - (margin.top / 2))
        .attr("text-anchor", "middle")  
        .style("font-size", "16px") 
        .style("text-decoration", "underline")  
        .text("Value vs Date Graph");
And the end result will look like this;
A nice logical place to put the block of code would be towards the end of the JavaScript. In fact I would put it as the last element we add. So here;
svg.append("g")         // Add the Y Axis
        .attr("class", "y axis")


Now since the vast majority of the code for this block is a regurgitation of the axis labels code, I don't want to revisit that and bloat up this document even more, so I will direct you back to that section if you need to refresh yourself on any particular line. But..... There are a couple of new ones in there which could benefit from a little explanation.

Both of them are style descriptors and as such their job is to apply a very specific style to this element.
     .style("font-size", "16px") 
     .style("text-decoration", "underline") 

What they do is pretty self explanatory. Make the text a specific size and underline it. But what is perhaps slightly more interesting is that we have this declaration in the JavaScript code and not in the CSS portion of the file.

Because strictly speaking, this is the sort of thing that would be placed in the <style> section of the HTML code, but in this case since it is only going to be used the once, we shouldn't feel too bad putting it here.

The above description (and heaps of other stuff) is in the D3 Tips and Tricks document that can be accessed from the downloads page of d3noob.org.  


  1. I think it's best to include a class attribute on your text element, and rather than setting the style in the javascript file, set it in a CSS file.

    1. I actually agree whole heatedly, but for better or worse I would like to encourage people to realize that on of d3.js's strengths is the manipulation of DOM elements. This may or may not be the best way to try and reinforce the message. I'm actually in the process of writing a separate section focusing on d3.js and the DOM, so perhaps that will help more. Thanks for the observation.