我正在使 X 轴显示年份。但是它不起作用,我的 cx 值为 0。我的猜测是 d3.timeFormat
解析年份值出现问题。
//d3.format year as yyyy
let dateFormat = d3.timeFormat("%Y");
//Define x and y scale range
let xScale = d3.scaleTime()
.range([0, width])
//Define x and y axis
let xAxis = d3.axisBottom(xScale)
.ticks(10)
.tickFormat(d =>
dateFormat(d))
xScale.domain(d3.extent(data, d =>
dateFormat(d.year)
))
let circles = svg.selectAll("circle")
.data(data)
.enter()
.append("circle");
circles
.attr("cx", d =>
xScale(dateFormat(+d.year)))
.attr("cy", d =>
yScale(d.emissions))
.attr("r", 4)
.style("fill", "blue")
当前输出:
期望的输出:
最佳答案
d3.timeParse这就是您正在寻找的。
由于data
仅包含year
作为数字,因此您必须使用d3.timeParse
将其解析为完整日期。方法如下:
- 定义解析器:
let parseDate = d3.timeParse("%Y")
根据上述解析数据:
data.forEach(function (d) { d.year = parseDate(d.year); });
并且
tickFormat
将更改为:.tickFormat(d => d.getFullYear())
( Date.getFullYear ) 正如您尝试的那样只需打印年份即可。这是您的代码笔的一个分支: https://codepen.io/shashank2104/pen/MzaoZp
希望这有帮助。
关于javascript - d3.timeScale() X轴不显示年份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53173474/