Question

I am working with JSON like the following:

[
    {
        "source": "Google",
        "date": "2014-02-01",
        "spend": 21,
        "clicks": 1000
    },
    {
        "source": "Bing",
        "date": "2014-02-01",
        "spend": 5,
        "clicks": 541
    },
    {
        "source": "Google",
        "date": "2014-02-02",
        "spend": 24,
        "clicks": 1029
    },
    {
        "source": "Bing",
        "date": "2014-02-02",
        "spend": 12,
        "clicks": 754
    }
]

And want to feed it into Crossfilter to create a line chart with NVD3. I don't know where to start, but I want the line chart to use the following:

  • X Axis - Date
  • Y Axis - Clicks
  • 1 line per source

This is what I've been able to build without Crossfilter:

(function () {
    var ymdFormat = d3.time.format('%Y-%m-%d');
    d3.json('./data.json', function (err, json) {
        nv.addGraph(function () {
            var chart = nv.models.lineChart()
            chart.margin({ left: 100 })
                     .useInteractiveGuideline(true)
                     .transitionDuration(350)
                     .showLegend(true)
                     .showYAxis(true).showXAxis(true);
            chart.xAxis
                     .axisLabel('Date')
                     .tickFormat(function (d) {
                            return d3.time.format('%b %Y')(new Date(d));
                     });
            chart.yAxis
                     .axisLabel('Clicks')
                     .tickFormat(d3.format(','));

            data = parseData(json);

            d3.select('#graph').append('svg')
                .datum(data).call(chart);
        });
    })

    function parseData(json) {
        var data, result, key;
        data = {};
        json.forEach(function (elmt) {
            if (!(elmt.source in data)) {
                data[elmt.source] = { values: [] }
            }
            data[elmt.source].values.push({ x: ymdFormat.parse(elmt.date), y: elmt.clicks })
        });

        result = [];
        for (key in data) {
            if (data.hasOwnProperty(key)) {
                result.push({
                    key: key,
                    values: data[key].values
                });
            }
        }
        console.log(result);
        return result;
    }
})()
Was it helpful?

Solution

I have this problem. I have a solution for this, not very nice, however.

var filterByMonthSource = filter.dimension(function(d) { return d.date + ':' + d.source });
var clicksGroup = filterByMonth.group().reduceSum(function(d) { return d.clicks });
var clicksData = clicksGroup.all();

clicksData will have [{key: "2014-02-01:Google", value: ...}, ...]

I then have to break clicksData into array of 3 fields.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top