D3.js时间刻度刻度-仅限年和月-自定义时间格式

D3.js time scale tick marks - Years and months only - Custom time format

本文关键字:自定义 格式 时间 时间刻度 js D3      更新时间:2023-09-26

我正在尝试制作一个可缩放图表,时间刻度在x轴上。

默认行为带有类似这样的xScale:

var x = d3.time.scale()
  .domain([getDate(minDate), getDate(maxDate)])
  .range([0, width]);

和一个类似的xAxis:

var xAxis = d3.svg.axis()
  .scale(x);

几乎就是我想要的。

但我希望有一个自定义的时间格式,显示年份,而不是显示月份的名称,只显示一条刻度线,没有文本(也许可以向这些刻度添加一个类),同时仍然保留缩放时轴的默认行为。

任何帮助都将不胜感激。

请参阅此处的JSfiddle

编辑:我认为Lars在这里的回答是一个很好的方法,只要它可以应用于可缩放的图表。有新的想法吗?

这可能会起作用。显示年份,而不是显示月份的名称,只显示一条刻度线,没有文本:

var timeAxis = d3.svg.axis()
        .scale(timeScale)
        .orient('bottom')
        .ticks(d3.time.years, 1)//should display 1 year intervals
        .tickFormat(d3.time.format('%Y'))//%Y-for year boundaries, such as 2011
        .tickSubdivide(12);//subdivide 12 months in a year

资源:

  1. d3.js大小刻度样式(http://bl.ocks.org/vjpgo/4689130)
  2. scale.ticks和scale.tickFormat()(https://github.com/mbostock/d3/wiki/Time-Intervals#year)

每两小时显示一次刻度的示例代码,并将其格式化为仅显示小时和AM/PM:

var timeAxis = d3.svg.axis()
        .scale(timeScale)
        .orient('bottom')
        .ticks(d3.time.hours, 2)
        .tickFormat(d3.time.format('%I%p'));

我最终编写了一个小函数来检查缩放级别并相应地设置轴的刻度量。

function calcTickAmount() {
  if (d3.event.scale > 15) {
    return 3
  } else {
    return 10;
  }
}

然后该函数将在更新函数中调用

function draw() {
  xAxis.ticks(calcTickAmount());
  axes.call(xAxis);
}

// Config SVG
var width = 500,
  height = 300,
  minDate = '1860',
  maxDate = '1958';
// Draw SVG element
var svgSelect = d3.select('div.tl').append('svg');
// Translate SVG G to accomodate margin
var translateGroupSelect = svgSelect
  .attr('width', width)
  .attr('height', height)
  .append('g');
// Define d3 xScale
var x = d3.time.scale()
  .domain([new Date(minDate), new Date(maxDate)])
  .range([0, width]);
// Define main d3 xAxis
var xAxis = d3.svg.axis()
  .scale(x)
  .ticks(10);
// Draw axes
var axes = translateGroupSelect.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + 0 + ")")
  .call(xAxis);
// Define zoom
var zoom = d3.behavior.zoom()
  .x(x)
  .scaleExtent([1, 32])
  .center([width / 2, height / 2])
  .size([width, height])
  .on("zoom", draw);
// Apply zoom behavior to SVG element
svgSelect.call(zoom);
// Repetitive drawing stuff on every zoom event
function draw() {
  xAxis.ticks(calcTickAmount());
  axes.call(xAxis);
}
function calcTickAmount() {
  if (d3.event.scale > 15) {
    return 3
  } else {
    return 10;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
<div class="tl">
</div>

更新的Fiddle