javascriptchartsplottable

Create Plottable.js stacked bar chart using the same dataset


I am trying to create stacked bar chart using plottable.js from the same dataset. Is it possible?

Here is my sample dataset

var data = [{ x: 0, y: 1, m: 10 },
            { x: 1, y: 1, m: 9 },
            { x: 2, y: 3, m: 5 },
            { x: 3, y: 2, m: 5 },
            { x: 4, y: 4, m: 8 },
            { x: 5, y: 3, m: 7 },
            { x: 6, y: 5, m: 5 }];

In the example posted on http://plottablejs.org/components/plots/stacked-bar/, it used two dataset.

var plot = new Plottable.Plots.StackedBar()
           .addDataset(new Plottable.Dataset(primaryData).metadata(5))
           .addDataset(new Plottable.Dataset(secondaryData).metadata(3))
           .x(function(d) { return d.x; }, xScale)
           .y(function(d) { return d.y; }, yScale)
           .attr("fill", function(d, i, dataset) { return dataset.metadata(); }, colorScale)
           .renderTo("svg#example");

My question is, since I am using the same dataset and I need to change the 'y' function into two distinct functions to something like this:

.y(function(d) { return d.y; }, yScale)
.y(function(d) { return d.m; }, yScale)

Is it possible? If yes, how?

Thanks...


Solution

  • You can create two different Plottable.Datasets based on the same data.

    So start like this:

    var ds1 = new Plottable.Dataset(data);
    var ds2 = new Plottable.Dataset(data);
    

    However, later you'll need to distinguish the two datasets to know which attribute to use, so you should add metadata

    var ds1 = new Plottable.Dataset(data, {name: "ds1"});
    var ds2 = new Plottable.Dataset(data, {name: "ds2"});
    

    now later, you can reference the name of the dataset to know which value to return in the .y() call

    plot.y(function(d, i, ds){
      if(ds.metadata().name == "ds1"){
        return d.y;
      }
      else{
        return d.m;
      }
    }, yScale);