d3.js - 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);
});
我无法确定折线图为何显得脱节。为什么这些点不相互连接。
解决方案
推荐阅读
- typescript - 使用 axios 处理来自 GraphQL API 的响应
- python - 从 2 个元组列表中查找公共值,并将一个元组中的值添加到另一个
- java - Android 自定义选择器意图仅显示三个选项
- java - 为什么 ParNew gc 第二次花费了太多时间?
- geolocation - iOS 和 android 是否支持 PWA 的室内定位系统?
- javascript - 使用 Reactstrap 和 Hashrouter,如何使用 Navbar 中的 DropdownItem 作为到其他页面的 Navlink?
- javascript - ajax获取数据请求url未找到但已经存在,Laravel 8
- html - 是否有 CSS 属性来控制或设置 div 每一边的长度
- arrays - 具有整数循环计数器的索引 MIPS 数组
- asp.net-core - 这很令人困惑.. 我正在创建 .net 核心 Web 应用程序,并且可以看到 .NetFramework 支持 .NetCore