使用相同的数据集创建Plottable.js堆叠条形图

Create Plottable.js stacked bar chart using the same dataset

本文关键字:js Plottable 条形图 创建 数据集      更新时间:2023-09-26

我试图从相同的数据集使用plottable.js创建堆叠条形图。这可能吗?

这是我的样本数据集

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 }];

在http://plottablejs.org/components/plots/stacked-bar/上发布的示例中,它使用了两个数据集。

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");

我的问题是,因为我使用相同的数据集,我需要将'y'函数更改为两个不同的函数,如下所示:

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

有可能吗?如果是,怎么做?

谢谢…

您可以基于相同的数据创建两个不同的Plottable.Dataset

所以像这样开始:

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

但是,稍后您需要区分两个数据集以知道使用哪个属性,因此您应该添加元数据

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

现在稍后,您可以引用数据集的名称,以知道在.y()调用

中返回哪个值。
plot.y(function(d, i, ds){
  if(ds.metadata().name == "ds1"){
    return d.y;
  }
  else{
    return d.m;
  }
}, yScale);