首页 > 解决方案 > 在 D3.js v6 中为日期字段自动调整轴刻度增量以避免重叠的最佳方法是什么?

问题描述

我目前有一个简单的折线图,它显示 y/x 轴的数据和日期。

样本数据输入:

[{ "week": "15/11/2020","index": 120}, { "week": "06/11/2020","index": 119}]

当显示的数据条目过多导致 x 轴标签相互重叠时,它在某个点上工作得很好。

我将如何配置刻度增量以自动调整小数据集的使用周数和大型数据集的月和年。

注意:我不打算轮换标签,因为它会在庞大的数据集上出现同样的过度拥挤问题

数据转储前:

在此处输入图像描述

数据转储后:

在此处输入图像描述

这里大多数相同性质的现有答案都来自 8 年前,是否有关于如何在更高版本的 D3(v5 - v6)中修复它的更新?

这是我的 d3 代码:

const xScale = scaleTime()
  .range([0, width])
  .domain(
    extent(data, (d: { week: any }) => {
      return d.week;
    })
  );

const yScale = scaleLinear()
  .range([height, 0])
  .domain([
    min(data, (d: { index: number }) => {
      return d.index;
    }) - 20,
    max(data, (d: { index: number }) => {
      return d.index;
    }) + 20
  ]);

const xAxis = axisBottom(xScale)
   .ticks(data.length);

const svg = select(svgRef.current);

svg
  .select(".x-axis")
  .style("transform", `translateY(${height}px)`)
  .call(xAxis);

const yAxis = axisLeft(yScale);
svg
  .select(".y-axis")
  .call(yAxis);

const myLine = line()
  .x((d: { week: any }) => xScale(d.week))
  .y((d: { index: any }) => yScale(d.index))
  .curve(curveCardinal);

svg
  .selectAll(".line")
  .data([data])
  .join("path")
  .attr("class", "data-circle")
  .attr("d", myLine)
  .attr("fill", "none")
  .attr("stroke", "purple")
  .attr("stroke-width", "5px");

  // draw circle here -- TODO
  svg
  .selectAll(".data-circle")
  .data([data])
  .append("circle")
  .attr("r", 7.5);

标签: javascriptreactjsd3.js

解决方案


推荐阅读