使用javascript express路由将JSON加载到C3.js中

时间:2017-01-23 16:51:09

标签: javascript json node.js ejs c3.js

我正在尝试使用c3.js绘制图形。我能够按照入门的方式进行操作,因此我知道模块工作正常,但是当我尝试使用自己的数据时,我的图形无法显示。

我从数据库中获取数据并将其存储起来:

MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  console.log("Connected successfully to server");
  findDocuments(db, function(docs){
      //console.log(docs);
      exports.getData = function(){
        return docs;
      }
    db.close();
  });
});

我知道这确实有效,它以长字符串提供以下输出:

[{"_id":"5885dc66c2ef160d2163fb79",
 "temperature":18,
 "humidity":27,
 "visibleLight":260,
 "irLight":255,
 "date":"2017-01-23T10:35:16+00:00",
 "epochtime":1485167716703}]

然后使用index.js将此数据加载到我的视图中,如下所示:

router.get('/', function (req, res) {
  res.render('index', { 
    title: 'Dashboard', 
    allData: db.getData()
  });
})

根据这些样本:http://c3js.org/samples/data_json.html 我试图绘制图表:

var chart = c3.generate({
  data: {
    json: allData,
    keys: {
      x: 'date', // it's possible to specify 'x' when category axis
      value: ['temperature', 'humidity'],
    }
  },
  axis: {
    x: {
      type: 'timeseries'
    }
  }
});

1 个答案:

答案 0 :(得分:0)

这里的问题是你缺少定义时间戳的定义。 c3 / d3应该如何知道你使用的是哪种模式?

var chart = c3.generate({
    data: {
            //use xFormat to define how your pattern looks like
            xFormat: '%Y-%m-%dT%H:%M:%S+00:00',
            json: [ 
                // your awesome data
            ],
            keys: {
                x: 'date',
                value: ['temperature', 'humidity'],
            }
        },
        axis: {
            x: {
                type: 'timeseries',
                tick: {
                //use tick.format to change how your pattern
                //will look in your chart (maybe more user friendly)
                format: '%Y-%m-%d'
                }
            }
        }
});

由于您的时区偏移量看起来非常奇怪(+00:00),您应该查看d3的concatenating以获得所需的模式。