【问题标题】:Bar graph on time axis with plottable.js - bar positions带有 plottable.js 的时间轴上的条形图 - 条形位置
【发布时间】:2016-09-08 15:39:48
【问题描述】:

如何使用 plottable.js 库将条形与相关日期对齐?第一个柱形数据来自周三 7 日,第二个来自周四 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();
});

【问题讨论】:

标签: javascript d3.js graph plottable


【解决方案1】:

我找到了简单的解决方案。我们需要为每个日期添加 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();
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-02
    • 2019-06-01
    • 2014-06-06
    • 1970-01-01
    相关资源
    最近更新 更多