D3.js Multiple Line Plot – Part 3

Working version of the plot, download here.

The data is now imported and loaded into memory. The next step is to attach each time-series to the DOM as an element. Before doing that, draw the initial axes.

Drawing the initial axes are easy with D3. Nothing too crazy, the y-axis has the text: “Relative Power.” However, note that the y-axis has been scaled (part 2) based on all the time-series. If a single time-series is removed, the y-axis should be re-scaled and re-drawn. The entire plot will also have to be re-drawn. Removing and added lines will be the subject of later posts.

        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")

        .attr("class", "y axis")
        .attr("transform", "translate(" + width + " ,0)")
        .attr("y", 6)
        .attr("dy", "-.71em")
        .style("text-anchor", "end")
        .text("Relative Power");

Now the initial lines can be drawn on the plot. Since the initial state of the svg selection contains no child elements having the “.index” keyword, the D3 selection: svg.selectAll(".index") will return with an empty selection. Thus, the combination of the .data(indices) and .enter().append("g") D3 functions will append a “g” element for every map key in the index object. Each “g” element will have an “id” and “class” based on the individual time-series “name” attribute.

For each time-series object attached to the index selection, the .append("path") function will create a “path” element. This path will be drawn based on the values entry of the individual time-series map. The function(d) in the D3 callback of .attr() implicitly iterates over all key-pairs in the index selection and all key-pair in each time-series. The line and color functions were initialized in part 1.

    index = svg.selectAll(".index")
        .attr("id", function(d) {
            return "index" + d.name;
        .attr("class", function(d) {
            return "index a" + d.name;

        .attr("class", "line")
        .attr("d", function(d) {
            return line(d.values);
        .style("stroke", function(d) {
            return color(d.name);