使用D3创建简单的轴底

问题描述 投票:2回答:1

我想使用D3创建一个非常简单的下轴。

这是我的代码:

const margin = { top: 20, right: 20, bottom: 20, left: 20 }
const width = 600
const height = 50
const widthWithoutMargins = width - margin.left - margin.right
const heightWithoutMargins = height - margin.top - margin.bottom

const domain = [
  new Date(2020, 11, 10, 22, 30),
  new Date(2020, 11, 10, 23, 0),
  new Date(2020, 11, 10, 23, 30),
  new Date(2020, 11, 11, 0, 0),
  new Date(2020, 11, 11, 0, 30),
  new Date(2020, 11, 11, 1, 0),
  new Date(2020, 11, 11, 1, 30),
]
const range = [0, widthWithoutMargins]
const scaleX = d3.scaleTime().domain(domain).range(range)
const axis1 = d3.axisBottom(scaleX)

const svg = d3.select('body')
  .append('svg')
  .attr('width', width)
  .attr('height', height)
  .append('g')
  .attr('transform', `translate(${margin.left}, ${margin.top})`)

svg.append('g')
  .attr('width', widthWithoutMargins)
  .attr('height', heightWithoutMargins)
  .attr('transform', `translate(0, ${heightWithoutMargins})`)
  .call(axis1);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

如您所见,我创建了一个范围为[0, 560]的时间刻度。

结果是这样:

enter image description here

enter image description here

路径元素似乎正确,宽度似乎正确。问题在于刻度线的位置,许多刻度线位于刻度线范围之外的路径的右侧。为什么?

javascript d3.js axis
1个回答
1
投票

问题是领域。正如您所看到的,scaleTime类似于连续刻度,并且接受两个日期组成的数组作为域,因此,极端情况,并非数据的所有日期都像分类刻度。

您必须以这种方式更改代码:

in the official documentation
const margin = { top: 20, right: 20, bottom: 20, left: 20 }
const width = 600
const height = 50
const widthWithoutMargins = width - margin.left - margin.right
const heightWithoutMargins = height - margin.top - margin.bottom

const dates = [
  new Date(2020, 11, 10, 22, 30),
  new Date(2020, 11, 10, 23, 0),
  new Date(2020, 11, 10, 23, 30),
  new Date(2020, 11, 11, 0, 0),
  new Date(2020, 11, 11, 0, 30),
  new Date(2020, 11, 11, 1, 0),
  new Date(2020, 11, 11, 1, 30),
]
const domain = d3.extent(dates)
const range = [0, widthWithoutMargins]
const scaleX = d3.scaleTime().domain(domain).range(range)
const axis1 = d3.axisBottom(scaleX)

const svg = d3.select('body')
  .append('svg')
  .attr('width', width)
  .attr('height', height)
  .append('g')
  .attr('transform', `translate(${margin.left}, ${margin.top})`)

svg.append('g')
  .attr('width', widthWithoutMargins)
  .attr('height', heightWithoutMargins)
  .attr('transform', `translate(0, ${heightWithoutMargins})`)
  .call(axis1);
© www.soinside.com 2019 - 2024. All rights reserved.