【问题标题】:d3 linechart - Show 0 on the y-axis without passing in all points?d3折线图 - 在y轴上显示0而不传递所有点?
【发布时间】:2013-05-24 11:08:32
【问题描述】:

我有一个折线图。其目的是显示给定时间段内每个用户的交易量。

为此,我要获取所有用户交易的日期。我正在处理这个例子:http://bl.ocks.org/mbostock/3884955 并且折线图渲染得很好。

我的 x 轴是时间,y 轴是交易次数。我遇到的问题是在没有活动时显示日期。

假设我周二有 4 笔交易,周四有 5 笔交易。我需要证明周三有 0 笔交易。由于我的数据库中不存在明确说明用户在星期三没有进行任何交易的数据,我是否需要在星期三时间(以及所有其他时间,取决于时间范围)以 0 值传递?或者我可以用 d3 来做吗?我似乎找不到任何适合我的问题的例子。

【问题讨论】:

    标签: d3.js linechart


    【解决方案1】:

    这似乎是一个很常见的问题,所以我在这里编写了一个示例实现:http://jsfiddle.net/nrabinowitz/dhW2F/2/

    相关代码:

      // get the min/max dates
      var extent = d3.extent(data, function(d) { return d.date; }),
          // hash the existing days for easy lookup
          dateHash = data.reduce(function(agg, d) {
              agg[d.date] = true;
              return agg;
          }, {}),
          // note that this leverages some "get all headers but date" processing
          // already present in the example
          headers = color.domain();
    
        // make even intervals
        d3.time.days(extent[0], extent[1])
            // drop the existing ones
            .filter(function(date) {
                return !dateHash[date];
            })
            // and push them into the array
            .forEach(function(date) {
                var emptyRow = { date: date };
                headers.forEach(function(header) {
                    emptyRow[header] = null;
                });
                data.push(emptyRow);
            });
        // re-sort the data
        data.sort(function(a, b) { return d3.ascending(a.date, b.date); });
    

    如您所见,它有点复杂,但似乎效果很好 - 您使用方便的 d3.interval.range 方法创建一个间隔均匀的日期数组,过滤掉数据中已经存在的日期,并使用剩余的日期推空行。一个缺点是大型数据集的性能可能会很慢 - 这假设整行都是空的,而不是不同系列中的不同空日期。

    另一种表示形式,有间隙(使用line.defined)而不是零点,在这里:http://jsfiddle.net/nrabinowitz/dhW2F/3/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-17
      • 1970-01-01
      相关资源
      最近更新 更多