Charts D3.js:仅在单个X轴坐标上绘制数据

Charts D3.js:仅在单个X轴坐标上绘制数据,charts,plot,d3.js,line,axis,Charts,Plot,D3.js,Line,Axis,我很难弄清楚为什么我的数据没有绘制在我创建的折线图上。我使用的是一个以年为单位的时间尺度,并已设法使图表的框架按预期呈现(X轴值显示为年)。但是,数据没有打印出来。以下是我的代码(console.log输出显示在脚本下面): console.log输出: year ["1911", "1912", "1913", "1914", "1915", "1916", "1

我很难弄清楚为什么我的数据没有绘制在我创建的折线图上。我使用的是一个以年为单位的时间尺度,并已设法使图表的框架按预期呈现(X轴值显示为年)。但是,数据没有打印出来。以下是我的代码(console.log输出显示在脚本下面):

console.log输出:

year 
["1911", "1912", "1913", "1914", "1915", "1916", "1917", "1918", "1919", "1920", "1921", "1922"...]

nomGDP 
[34675, 37745, 39517, 36831, 39048, 50117, 60278, 76567, 79090, 89246, 74314, 74140, 86238...]

x domain 
[Sun Jan 01 1911 00:00:00 GMT-0500 (EST), Tue Jan 01 2013 00:00:00 GMT-0500 (EST)]

x range [0, 760]

y1 domain [0, 16244600] 

y range [320, 0] 


Plotting X1 value for data point: 34675 using index: 1911 to be at ( x(i) ) : 439.60279328609266 using our xScale. bloch-new.html:150
Plotting Y1 value for data point: 34675 to be at ( y1(d) ): 319.3169422454231 using our y1Scale. bloch-new.html:157
Plotting X1 value for data point: 37745 using index: 1912 to be at ( x(i) ) : 439.6027932863288 using our xScale. bloch-new.html:150
Plotting Y1 value for data point: 37745 to be at ( y1(d) ): 319.25646676434013 using our y1Scale. bloch-new.html:157
...
Plotting X1 value for data point: 15533800 using index: 2011 to be at ( x(i) ) : 439.60279330970303 using our xScale. bloch-new.html:150
Plotting Y1 value for data point: 15533800 to be at ( y1(d) ): 14.001945261810022 using our y1Scale. bloch-new.html:157
Plotting X1 value for data point: 16244600 using index: 2012 to be at ( x(i) ) : 439.60279330993916 using our xScale. bloch-new.html:150
Plotting Y1 value for data point: 16244600 to be at ( y1(d) ): 0 using our y1Scale. 
从上面的控制台输出可以看到,数据仅以439的X值打印。你知道为什么吗?域和范围输出似乎正确


此时,您的代码将返回该年的字符串作为该行的x坐标。您需要将其传递到您的秤上,并正确设置。这还需要将年份解析为日期。总之,您的代码看起来是这样的

.x(function(d, i) {
  return x(parse(year[i]));
})
一般来说,D3实现这一点的方法是在单个数组中包含年份和值,然后将其传递给
.data()
函数。那么你的线函数看起来像

var line = d3.svg.line()
             .x(function(d) { return x(d.year); })
             .y(function(d) { return y(d.nomGDP); });
以及添加行的代码

graph.selectAll("path").data([data]).enter()
     .append("path")
     .attr("d", line);

您可能希望
返回x(解析(年份[i])行1的
.x()
函数中使用code>。完美!谢谢你的建议。我会再加上一些解释作为回答。谢谢拉尔斯。我从几个不同的例子中得出结论。具体而言,以及
graph.selectAll("path").data([data]).enter()
     .append("path")
     .attr("d", line);