Search code examples
javascriptd3.jslegenddonut-chart

D3 donut chart based on seasons with fixed labels


After successfully creating a few charts using D3 I'm now trying to create a legend for a map that looks like this:

Example of a donut chart as a legend.

This is a representation of the seasons troghout a year, illustrated by colours beneath fixed labels indicating each month of a year (in the image they're rounded down to months, I don't want that to happen in the donut chart I'm trying to create).

Now I thought I'd start out by following an example of a donut chart on the D3js page, and then add some sort of fixed labels afterwards. Before getting to that point though I find myself stuck and unable to replicate the example.

I've tried to make a concise example using Plunkr here, and I'm wondering if anyone would take a look. I've followed an approach outlined here to use a created object as data input, I don't see anything wrong with that yet, but maybe I'm mistaken. The error message I'm getting is as follows:

Uncaught TypeError: Cannot read property 'indexOf' of undefined: Main.js(1494)

Line 1494 corresponds to line 37 on the Plunkr, reading:

.append(g)

This leads me to believe that something is going wrong when I point d3 to the data, but I'm unsure what this is. I'd appreciate a fresh pair of eyes looking of it!


Solution

  • You have a couple of problems:

    First, you forgot to change population after copying/pasting Bostock's example. I changed it for dur:

    var pie = d3.layout.pie()
    .sort(null)
    .value(function(d) {
      return d.dur
    });
    

    After that, I had to change your data:

      var data = [
    { seizoen: "lente", dur: 60 }, 
    { seizoen: "zomer", dur: 122 },
    { seizoen: "herfst", dur: 61 },
    { seizoen: "winter", dur: 122 }
    ];
    

    Also, you forgot to use # to select the ID of the div:

     var svg = d3.select("#legend").append("svg")
    

    Btw, your path to jquery was incorrect, and the #legend in your CSS was very little.

    Now you have a donut: http://plnkr.co/edit/B2CJMN7Wy1By0jlMpkii?p=preview