使用c3.js将数据添加到图表

时间:2017-09-21 02:48:12

标签: javascript d3.js c3.js

我有一个图表,其中我想添加更多数据而不用我的数据替换,使用.push或添加一组数据而不会丢失我以前拥有的数据。

我该怎么做?

columns: [
      ['data1', -4,3,4,7,8,9,8,7,3],
      ['data1_x', -5,2,3,4,5,4,3,2,1],

。 。

//I need add the new data withouth remove the previous data

chart.load({
    xs: {
        data1: 'data1_x'
    },
    columns: [
        ["data1_x", 3,6],
        ["data1", 5,8]
    ]
});

https://jsfiddle.net/aL8xhgpn/

1 个答案:

答案 0 :(得分:2)

您可以将数据移动到数组

var data1 = ['data1',-4,3,4,7,8,9,8,7,3];
var data1_x = ['data1_x', -5,2,3,4,5,4,3,2,1];

并将数据推入其中。

下面的工作示例。

var data1 = ['data1', -4, 3, 4, 7, 8, 9, 8, 7, 3];
var data1_x = ['data1_x', -5, 2, 3, 4, 5, 4, 3, 2, 1];
var chart = c3.generate({
  data: {
    xs: {
      data1: "data1_x",
      data2: "data2_x"
    },
    xSort: false,
    columns: [
      data1,
      data1_x, ['data2', Math.random() * 10, Math.random() * 10, Math.random() * 10, Math.random() * 10, Math.random() * 10, Math.random() * 10],
      ['data2_x', Math.random() * 10, Math.random() * 10, Math.random() * 10, Math.random() * 10, Math.random() * 10, Math.random() * 10]
    ]

  },
  axis: {
    x: {
      tick: {
        values: d3.range(-5, 10)
      }
    }
  }
});

chart.internal.xAxis.g.attr('transform', "translate(0," + chart.internal.y(0) + ")");
chart.internal.yAxis.g.attr('transform', "translate(" + chart.internal.x(0) + ", 0)");
data1.push(5)
data1.push(8)
data1_x.push(3)
data1_x.push(6)


setTimeout(load, 5000);

function load() {
  chart.load({
    xs: {
      data1: 'data1_x'
    },
    columns: [
      data1_x,
      data1
    ]
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.18/c3.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.18/c3.js"></script>
<div id="chart"></div>