javascript - 仅显示天数时间刻度

标签 javascript d3.js

我正在尝试从scaleTime的x轴上删除月份和年份刻度,但不知道是否可能:

xAxis of scaleTime

我尝试使用tickFormat 方法,但无法访问月份和年份值。我只能通过将比例更改为 LinearScale 并手动格式化值来获得预期结果。

有可能在时间尺度上得到预期的结果吗?

const margin = { top: 20, right: 20, bottom: 20, left: 20 };
const width = 1000 - margin.top - margin.bottom;
const height = 100 - margin.left - margin.right;
const totalWidth = width + margin.top + margin.bottom;
const totalHeight = height + margin.left + margin.right;

let svg = d3.select('.chart')
  .append('svg')
    .attr('width', totalWidth)
    .attr('height', totalHeight)
  .append('g')
    .attr('transform', `translate(${margin.left},${margin.top})`);

let xScale = d3.scaleTime()
  .rangeRound([0, width])
  .domain([
    new Date(1482883200000), // 2016-12-28
    new Date(1485993600000) // 2017-02-02
  ]);

let xAxis = d3
  .axisBottom(xScale);

svg.call(xAxis);
<script src="https://d3js.org/d3.v4.min.js"></script>
<div class="chart"></div>

最佳答案

由于很难知道轴生成器将如何显示时间刻度的刻度,因此我建议您在创建刻度后对其进行过滤:

d3.selectAll(".tick").each(function(d) {
    if (d3.timeFormat("%Y")(d) == d3.select(this).text() ||
        d3.timeFormat("%B")(d) == d3.select(this).text()) {
        d3.select(this).remove();
    }
})

这是演示:

const totalWidth = 800;
const totalHeight = 100;

let svg = d3.select('body')
    .append('svg')
    .attr('width', totalWidth)
    .attr('height', totalHeight);

let xScale = d3.scaleTime()
    .rangeRound([20, totalWidth - 20])
    .domain([
        new Date(1482883200000), // 2016-12-28
        new Date(1485993600000) // 2017-02-02
    ]);

let xAxis = d3.axisBottom(xScale);

svg.append("g").attr("transform", "translate(0,40)").call(xAxis);

var format = d3.timeFormat("%a %d");

d3.selectAll(".tick").each(function(d) {
    if (d3.timeFormat("%Y")(d) == d3.select(this).text() || d3.timeFormat("%B")(d) == d3.select(this).text()) {
        d3.select(this).remove();
    }
})
<script src="https://d3js.org/d3.v4.min.js"></script>

关于javascript - 仅显示天数时间刻度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42554514/

相关文章:

javascript - 将文本替换为 HTML 文件中的 html 标签

javascript - JQuery 删除/添加 Infopath webpart 的 ID 类

jquery - 如何在 Ajax 调用中获取最新的 csv 文件?

javascript - 如何使用 jQuery 多次复制列表元素

php - JS循环MySQL结果?

javascript - 单击链接时显示相关 div

javascript - 使用 D3 样条线时如何阻止图形被裁剪?

javascript - 平移传单 map 时 d3 SVG 被切断

javascript - 如何使用 d3.js 获取垂直方向的树

javascript - D3.js V5 - 为什么我的条形图轴不缩放?