【问题标题】:How to render dates on x axis prior to 1900 with d3 .js scatter plot如何使用 d3 .js 散点图在 1900 年之前的 x 轴上呈现日期
【发布时间】:2019-03-28 11:06:04
【问题描述】:

我的 d3 散点图使用从 1600 到现在的历史日期数据。我可以成功绘制我的点,但无法在 x 轴上显示 1900 年之前的日期。

我正在使用这个example to make a scatterplot in d3,但我的数据的历史日期早于 1900 年。我尝试实现 this solution,但这会返回每个刻度标记重复的单个日期

如果我尝试实现 d3.axisBottom(x),这会从我的数据中返回日期,但 1900 年之前的日期格式不正确。

我已经用完整的代码制作了plunker

这是我的相关比例和轴代码(来自 plunkr):

var x = d3.scaleTime().range([0, width]);
var y = d3.scaleLinear().range([height, 0]);

var xAxis = d3.axisBottom(x).ticks(10).tickFormat(function(d){return timeFormat(d);});
var yAxis = d3.axisLeft(y).ticks(10);

var x = d3.scaleTime()
  .domain(d3.extent(data, function(d) {return (d.dates);}))
  .range([ 0, width ]);

svg.append("g")
  .attr("transform", "translate(0," + height + ")")
  //.call(xAxis, function (d){return (d);});
  //.call(xAxis, function (d){return (d.dates);}); // returns just a single date for all tick marks
 .call(d3.axisBottom(x)); // partially correct dates but not formatting dates prior to 1900

我的散点图很好,点也符合预期。我想在 x 轴上看到的是 1900 年之前的日期,例如 1750 年。

非常感谢您的帮助。

【问题讨论】:

    标签: date d3.js


    【解决方案1】:

    引用的答案是正确的,您的代码中还有其他问题。 我还更新了该答案以清理代码并包含一个通用示例,其轴范围为 1600-2000。

    第一个问题是你定义了你的 x 比例:

    var x = d3.scaleTime().range([0, width]);
    

    然后几乎立即定义您的轴:

    var xAxis = d3.axisBottom(x)
      .tickFormat(timeFormat);
    

    然后定义 x 域,同时重新定义 x:

    var x = d3.scaleTime()
      .domain(d3.extent(data, function(d) {return (d.dates);}))
      .range([ 0, width ]);
    

    如果我们使用svg.call(xAxis),这意味着轴使用第一个 x 刻度域,默认为 [2000 年 1 月 1 日,2000 年 1 月 2 日],这就是为什么如果应用只有一个默认域的轴。

    您的代码有 .call(d3.axisBottom(x) 而不是 .call(xAxis),这会再次创建一个新轴,但没有呈现 1900 年前日期所需的格式

    相反,首先确定比例的域,然后创建轴:

    var x = d3.scaleTime()
      .range([0, width])
      .domain(d3.extent(data, function(d) {return (d.dates);}))
    
    var xAxis = d3.axisBottom(x)
      .tickFormat(timeFormat);
    

    现在您可以应用轴了:

    selection
      .attr("transform",...)
      .call(xAxis);
    

    这是更新后的plunkr

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-13
      • 2011-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-28
      • 2017-12-24
      相关资源
      最近更新 更多