首页 > 解决方案 > D3.js 奇怪的折线图

问题描述

我使用这个 D3 教程https://bl.ocks.org/d3noob/4db972df5d7efc7d611255d1cc6f3c4f作为参考。数据是https://www.kaggle.com/START-UMD/gtd

这是我的代码,

var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 1400 - margin.left - margin.right,
height = 720 - margin.top - margin.bottom;

// parse the date / time
var parseTime = d3.timeParse("%d-%b-%y");

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

// define the line
var valueline = d3.line()
.x(function(d) { return x(d.iyear); })
.y(function(d) { return y(d.nkill); });

var valueline2 = d3.line()
.x(function(d) { return x(d.iyear); })
.y(function(d) { return y(d.nwound); });

// append the svg obgect to the body of the page
// appends a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg2 = 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 + ")");

// Get the data
d3.csv("data/datafinal.csv", function(error, data) {
if (error) throw error;
data.forEach(function(d) {
  d.iyear = parseInt(d.iyear);
  d.nkill = +parseInt(d.nkill);
  d.nwound = +parseInt(d.nwound);
  //console.log(d.nkill)
});


// Scale the range of the data
x.domain(data.map(function(d) { return d.iyear; }));
y.domain([0, d3.max(data, function(d) { return d.nkill; })]);



// Add the X Axis
svg2.append("g")
  .attr("transform", "translate(0," + height + ")")
  .call(d3.axisBottom(x));

// Add the Y Axis
svg2.append("g")
  .call(d3.axisLeft(y));


svg2.append("text")
.attr("transform", "translate(" + (width+3) + "," + y(data[0].nkill) + 
")")
.attr("dy", ".35em")
.attr("text-anchor", "start")
.style("fill", "red")
.text("Killed");

svg2.append("text")
.attr("transform", "translate(" + (width+3) + "," + y(data[0].nwound) + 
")")
.attr("dy", ".35em")
.attr("text-anchor", "start")
.style("fill", "steelblue")
.text("Wounded");

 // Add the valueline path.
svg2.append("path")
  .data([data])
  .attr("class", "line")
  .attr("d", valueline);

svg2.append("path")
  .data([data])
  .style("stroke", "red")
  .attr("class", "line")
  .attr("d", valueline2);
 });

这是奇怪的输出: 在此处输入图像描述

我无法确定折线图为何显得脱节。为什么这些点不相互连接。

标签: d3.jsdata-visualizationlinechart

解决方案


推荐阅读