【问题标题】:d3 scale, put ticks every Nth day evenly spacedd3 刻度,每隔 N 天均匀放置刻度
【发布时间】:2020-10-13 07:03:01
【问题描述】:

我想每隔 N 天在我的图表上创建一个分时,可以配置天数。如果用户选择“30 天”,则刻度应每 30 天显示一次。

为此,我尝试使用d3.timeDay 传递一个间隔。问题是 D3 文档告诉我the dates are not uniformly spaced。此外,它不能超过 30 天。

d3.timeDay.every(30).range(new Date(2015, 0, 1), new Date(2015, 2, 1));
// returns
[
  2015-01-01,
  2015-01-31,
  2015-02-01,
]

如何获得均匀间隔的日期(和刻度?)

    const dom = [new Date(2019, 1, 1), new Date(2020, 1, 1)]

    const width = 600
    const height = 200
    const x = d3.scaleTime()
      .domain(dom)
      .range([0, width])

    d3.select("body")
      .append("svg")
      .attr("viewBox", [0, 0, width, height])
      .append("g")
      .call(d3.axisBottom(x)
        .ticks(d3.timeDay.every(30))
        .tickFormat(d3.timeFormat("%d-%m-%Y")))
<script src="https://d3js.org/d3.v6.min.js"></script>

【问题讨论】:

    标签: javascript d3.js


    【解决方案1】:

    我设法用d3.count() 做到这一点,过滤每个到来的日期并检查第一个日期的间距。如果有更好的解决方案,请随时回答。

        const dom = [new Date(2019, 1, 1), new Date(2020, 1, 1)]
    
        const width = 600
        const height = 200
        const x = d3.scaleTime()
          .domain(dom)
          .range([0, width])
    
        d3.select("body")
          .append("svg")
          .attr("viewBox", [0, 0, width, height])
          .append("g")
          .call(d3.axisBottom(x)
            .ticks(d3.timeDay.filter(d => d3.timeDay.count(dom[0], d) % 30 === 0))
            .tickFormat(d3.timeFormat("%d-%m-%Y")))
    <script src="https://d3js.org/d3.v6.min.js"></script>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-06
      • 1970-01-01
      • 1970-01-01
      • 2016-06-03
      • 1970-01-01
      相关资源
      最近更新 更多