javascript - d3.timeScale() X轴不显示年份

标签 javascript json d3.js

我正在使 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")

当前输出:

enter image description here

期望的输出:

enter image description here

Codepen

最佳答案

d3.timeParse这就是您正在寻找的。

由于data仅包含year作为数字,因此您必须使用d3.timeParse将其解析为完整日期。方法如下:

  1. 定义解析器:let parseDate = d3.timeParse("%Y")
  2. 根据上述解析数据:

    data.forEach(function (d) {
      d.year = parseDate(d.year);
    });
    
  3. 并且 tickFormat 将更改为: .tickFormat(d => d.getFullYear()) ( Date.getFullYear ) 正如您尝试的那样只需打印年份即可。

    这是您的代码笔的一个分支: https://codepen.io/shashank2104/pen/MzaoZp

希望这有帮助。

关于javascript - d3.timeScale() X轴不显示年份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53173474/

相关文章:

javascript - WordPress 作者页面描述换行/新行

javascript - 当使用 Javascript 选择链接时,如何隐藏 HTML 元素?

javascript - 将 Node 中收到的 POST 请求转换为 Javascript 对象

javascript - jQuery 从表中返回多于 1 行的数据

python - 将 Django 模型字段选择转换为 JSON

PHP 网络服务 : Get Multiple Records from MySQL and encode it in JSON array

java - 如何断言 JSON 数组中具有相同键但值不同的两个 JSON 对象

javascript - 单击按钮或输入搜索字段时使用新数据重绘 D3 饼图

javascript - 指定当用户单击时在圆弧上插入圆的起点

javascript - d3 力有向图向下力模拟