时间轴上的条形图与plottable.js - 条形位置

时间:2016-09-08 15:39:49

标签: javascript d3.js graph plottable.js plottable

如何使用plottable.js库对齐相关日期的栏?第一个酒吧数据来自Wed 7,第二个来自Thu 8。

这是JSFiddle示例:https://jsfiddle.net/50yq46cm/3/

function makeBasicChart() {

  var data    = [{"date":1473120000000,"count":0},{"date":1473206400000,"count":73},{"date":1473292800000,"count":3},{"date":1473379200000,"count":0},{"date":1473465600000,"count":0},{"date":1473552000000,"count":0},{"date":1473638400000,"count":0},{"date":1473724800000,"count":0}];
  var dataset = new Plottable.Dataset(data);

  var xScale  = new Plottable.Scales.Time();
  var yScale  = new Plottable.Scales.Linear();

  var xAxis   = new Plottable.Axes.Time(xScale, "bottom");
  var yAxis   = new Plottable.Axes.Numeric(yScale, "left");

  var plot    = new Plottable.Plots.Bar();

  plot.x(function (d) { return d.date; },   xScale);
  plot.y(function (d) { return d.count; },  yScale);
  plot.addDataset(dataset);

  var chart = new Plottable.Components.Table([
    [yAxis, plot],
    [null, xAxis]
  ]);

  chart.renderTo("svg#tutorial-result");

}

$(document).ready(function () {
  makeBasicChart();
});

1 个答案:

答案 0 :(得分:0)

我找到了简单的解决方案。我们需要为每个日期添加12小时,然后是正确位置的条形码。

JSFiddle在这里https://jsfiddle.net/gpfz62z4/4/

(代码略有改进。我添加了一些交互性(尝试鼠标),并将日期更改为字符串,因为条形大小是渲染更精确的方式。)

    function makeBasicChart() {

      var data    = [{"x":"2016-09-06 00:00","y":0},{"x":"2016-09-07 00:00","y":73},{"x":"2016-09-08 00:00","y":3},{"x":"2016-09-09 00:00","y":0},{"x":"2016-09-10 00:00","y":0},{"x":"2016-09-11 00:00","y":0},{"x":"2016-09-12 00:00","y":0},{"x":"2016-09-13 00:00","y":0}];
    var dataset = new Plottable.Dataset(data);

    var xScale  = new Plottable.Scales.Time().domain([new Date("2016-09-05"), new Date("2016-09-16")]);;
    var yScale  = new Plottable.Scales.Linear();

    var xAxis   = new Plottable.Axes.Time(xScale, "bottom");
    var yAxis   = new Plottable.Axes.Numeric(yScale, "left");

    var plot    = new Plottable.Plots.Bar();

    plot.addDataset(dataset);
    plot.x(function (d) { return (moment(new Date(d.x)).add(12, 'h')); }, xScale);
    plot.y(function (d) { return d.y; }                                 , yScale);
    plot.attr("width", function() { return xScale.scale(24*3600*1000) - xScale.scale(0); });

    var grid    = new Plottable.Components.Gridlines(xScale);
    var group   = new Plottable.Components.Group([plot, grid]);

    var chart = new Plottable.Components.Table([
      [yAxis, group],
      [null, xAxis]
    ]);

    chart.renderTo("svg#tutorial-result");
    pzi = new Plottable.Interactions.PanZoom(xScale, null).attachTo(chart);
  }

  $(document).ready(function () {
    makeBasicChart();
  });