[英]Parsing dates with d3.js v.4
我正在嘗試通過基於Free Code Camp課程的第一個d3 迷你項目來學習如何使用d3.js進行編碼。 我想用這個json文件制作一個簡單的條形圖。 我試圖格式化文件中的日期。 我已經嘗試過查看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 ,
返回的函數解析指定的字符串,返回相應的日期,如果根據此格式的說明符無法解析字符串,則返回null。
這就是你的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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.