dc.js - multiple lineChart based on separate categories in single csv file

99封情书 提交于 2019-12-25 04:07:11

问题


For example if I have the following csv file:

category, number, total A,1,3 A,2,5 A,3,1 B,1,4 B,2,6 B,3,1 C,1,5 C,2,2 C,3,4

I was able to follow the following example and separate out the data into different csv files and composing each one.

github link

However, I was wondering how would I recreate the same lineCharts if I were to only have a single csv file and separate each lineChart by each grouped category.

Thanks.


回答1:


@minikomi's answer is the straight d3 way to do this.

The dc.js/crossfilter way to do this (if you want your charts to reduce values for each key and interact/filter with other dc charts) is to reduce multiple values in a single group like this:

var group = dimension.group().reduce(
    function(p, v) { // add
        p[v.type] = (p[v.type] || 0) + v.value;
        return p;
    },
    function(p, v) { // remove
        p[v.type] -= v.value;
        return p;
    },
    function() { // initial
        return {};
});

https://github.com/dc-js/dc.js/wiki/FAQ#rows-contain-a-single-value-but-a-different-value-per-row

Then you can specify each line chart by passing the group along with an accessor to the .group method like so:

lineChartA.group(group, 'A', function(a) { return x.A; })
lineChartB.group(group, 'B', function(a) { return x.B; })

If you want to combine the line charts in a single chart, you can compose them with the composite chart or series chart




回答2:


You can reduce the data to give 3 different arrays, each which only contain data from each category:

var grouped = data.reduce(function(o,d) {
  if(o[d.category]) {
    o[d.category].push(d);
  } else {
    o[d.category] = [d];
  }
  return o;
}, {});

Usually in d3 we work with arrays of data, so I'd use d3.map to convert it to an array of pairs key / value

var lineData = d3.map(grouped).entries()

Now, you can use this to create your lines (leaving out creating scales x and y), svg element etc.:

var line = d3.svg.line()
             .x(function(d){return x(d.number)})
             .y(function(d){return y(d.total)})

var linesGroup = svg.append("g")

var lines = linesGroup.data(lineData).enter()
                      .append("line")
                      .attr("d", function(d){return line(d.value)})

You could also set the stroke color using the d.key for the d3.map entries (which will come from the key we used in the reduce step - the category). Don't forget to convert your csv data to numbers too using parseInt().



来源:https://stackoverflow.com/questions/27849643/dc-js-multiple-linechart-based-on-separate-categories-in-single-csv-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!