D3 - tickFormat无效

时间:2017-02-27 11:56:38

标签: javascript d3.js

如果有人可以查看我的代码并让我知道为什么D3不希望将Y轴刻度格式设置为%M:%S

JSFiddle

代码:

function renderScatterPlot(data) {

  // set up svg and bar dimensions/margins
  const width = 1000;
  const height = 500;
  const padding = 20;
  const margin = { top: 40, right: 20, bottom: 80, left: 80 };

  // append svg to DOM
  const svg = d3.select('body')
    .append('svg')
    .attr('width', width)
    .attr('height', height)

  // for parsing time string in data and converting back to original format
  const parse = d3.timeParse('%M:%S');
  const format = d3.timeFormat('%M:%S')

  // calculate min and max data values
  const timeMin = d3.min(data, (d) => parse(d.Time));
  const timeMax = d3.max(data, (d) => parse(d.Time));

  // set up scales
  const xScale = d3.scaleBand()
    .domain(data.map((d) => d.Year))
    .range([margin.left, width - margin.right])
    .paddingInner(0.1)

  const yScale = d3.scaleTime()
    .domain([timeMin, timeMax])
    .range([height - margin.bottom, margin.top])

  // set up x and y axes
  const xAxis = d3.axisBottom(xScale)

  const yAxis = d3.axisLeft(yScale)
    .tickFormat(format)


  // append axes to svg
  svg.append('g')
    .attr('id', 'x-axis')
    .attr('transform', `translate(0, ${height - margin.bottom})`)
    .call(xAxis)

  svg.append('g')
    .call(d3.axisLeft(yScale))
    .attr('transform', `translate(${margin.left}, 0)`)
    .attr('id', 'y-axis')
}

$.getJSON('https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/cyclist-data.json', (data) => renderScatterPlot(data));

1 个答案:

答案 0 :(得分:0)

D3正在格式化你的刻度,tickFormat工作得很好。

然而,这样做没有意义......

const yAxis = d3.axisLeft(yScale)
    .tickFormat(format)

...如果在调用轴时,您只需忽略yAxis

svg.append('g')
    .call(d3.axisLeft(yScale))

应该是:

svg.append('g')
    .call(yAxis)

这是您更新的小提琴:https://jsfiddle.net/swxbx0Lt/