javascript - 使用 d3.js v.4 解析日期

标签 javascript json d3.js

我正在尝试通过处理我的第一个 d3 mini project 来学习如何使用 d3.js 进行编码基于 Free Code Camp 类(class)。我正在尝试用这个 json file 制作一个简单的条形图.我在尝试格式化文件中的日期时遇到了困难。我试过查看 d3.js API我仍然迷路了。如果有任何建议,我将不胜感激。这是我的代码

    // set the dimensions and margins of the graph
var margin = {top: 20, right: 20, bottom: 30, left: 40},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

//then make a function to parse the time
var parseDate = d3.timeFormat("%Y-%m-%d");

// set the ranges
var x = d3.scaleBand().rangeRound([0, width]).padding(0.1);
var y = d3.scaleLinear().range([height, 0],0.5);

// append the svg object to the body of the page
// append a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", 
          "translate(" + margin.left + "," + margin.top + ")");


//setup axis


// get the data
d3.json("https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json").get(function(error,dataset){
  var d =dataset.data;
  d.forEach(function(datum, i) {
        d[0]=parseDate(datum[0]);
         //console.log(datum[1]);
    });
  //console.log(d[3][0]);

});

最佳答案

你想要timeParse,而不是timeFormat:

var parseDate = d3.timeParse("%Y-%m-%d");

使用 timeParse ,

the returned function parses a specified string, returning the corresponding date or null if the string could not be parsed according to this format’s specifier.

这就是您的 forEach 函数应该是这样的:

data.forEach(function(d) {
    d[0] = parseDate(d[0]);
});

这是一个演示:

var parseDate = d3.timeParse("%Y-%m-%d");

d3.json("https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json", function(json) {

    var data = json.data;

    data.forEach(function(d) {
        d[0] = parseDate(d[0]);
    });
  
    console.log(data);
  
});
<script src="https://d3js.org/d3.v4.min.js"></script>

关于javascript - 使用 d3.js v.4 解析日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41581284/

相关文章:

javascript - 将选择下拉框添加到onclick交换图像js

json - 将 colly 包输出文本添加到 golang 中的映射

javascript - 如何从d3中的json请求数据?

json - 如何添加具有默认值的 JSON 模式可选枚举项?

d3.js - 在 d3.js 中单击拖拽后未触发的事件(有时)

javascript - 是否可以使用这些数据在 nvd3.js 中生成图表?

javascript - 第一次在 chrome 浏览器中打印不工作

c# - 服务器端代码中的 HTML 输入值。网站

javascript - 强制 IE 清除图像

javascript - 将时间戳格式添加到折线图 x 轴