msunbot
msunbot

Reputation: 2001

Manipulating Javascript Data to Toggle Series on D3.js

I am following this example on flot (http://www.flotcharts.org/flot/examples/series-toggle/index.html) to apply the concept onto D3.js.

my data looks like this :

[ { "sourceA" : 28, "sourceB": 25, "sourceC": 20, "date": "29-Apr-13", 
"sourceA" : 15, "sourceB": 23, "sourceC": 54, "date": "29-May-13",
"sourceA" : 23, "sourceB": 43, "sourceC": 23, "date": "29-Jun-13",
}]

I have followed the source code of the above example to set up the checkboxes ("sourceA", "sourceB", etc). However, I'm stuck with how to manipulate data using "plotAccordingToChoices" function.

Ie, if the sourceA checkbox was selected, the function should change the data to:

[ { "sourceA" : 28, "date": "29-Apr-13", 
"sourceA" : 15, "date": "29-May-13",
"sourceA" : 23, "date": "29-Jun-13",
}]

Sample code from the example - http://www.flotcharts.org/flot/examples/series-toggle/index.html

// insert checkboxes 
    var choiceContainer = $("#choices");
    $.each(datasets, function(key, val) {
        choiceContainer.append("<br/><input type='checkbox' name='" + key +
            "' checked='checked' id='id" + key + "'></input>" +
            "<label for='id" + key + "'>"
            + val.label + "</label>");
    });

    choiceContainer.find("input").click(plotAccordingToChoices);

    function plotAccordingToChoices() {

        var data = [];

        choiceContainer.find("input:checked").each(function () {
            var key = $(this).attr("name");
            if (key && datasets[key]) {
                data.push(datasets[key]);
            }
        });

        if (data.length > 0) {
            $.plot("#placeholder", data, {
                yaxis: {
                    min: 0
                },
                xaxis: {
                    tickDecimals: 0
                }
            });
        }
    }

    plotAccordingToChoices();

Upvotes: 0

Views: 589

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109272

The code of your filter function would look something like the following.

function filter(json, attrName) {
  var newJson = [];
  json.forEach(function(d) {
    newJson.push({ "date": d.date, attrName: d[attrName] });
  });
  return newJson;
}

Upvotes: 1

Related Questions