我正在尝试使用d3.js绘制带有标签的x轴,我有一个从1950年到2015年的数据数组,我打算在x轴上绘制它们,从0年开始,但我的代码输出x轴从数组的最小值开始,如果编辑数组为0作为最小值,那么x轴标签会改变。任何提示我在哪里做错了?
我的代码输出:1950 ...... 1955 ...... 1960
包含年份0的输出,这不是我想要的: 0 .... .... 200 400 .......... 2015
我打算输出什么:0 ...... 1950 ...... 1955 ....
$.getJSON(
"https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json",
function(x) {
var rawData = x.data;
var yearData = [];
var gdpData = [];
var width = 1020;
var height = 100;
for (var i = 0; i < rawData.length; i++) {
yearData.push(rawData[0][0]);
gdpData.push(rawData[1][1]);
}
//values which should be labeled on x-axis
var years = [
1950,
1955,
1960,
1965,
1970,
1980,
1985,
1990,
2000,
2005,
2010,
2015
];
var svg = d3
.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
.append('g');
var x_domain = d3.extent(years, function(d) {
return d;
});
var xscale = d3
.scaleLinear()
.domain(x_domain)
.nice()
.range([20, 600]);
var x_axis = d3
.axisBottom()
.scale(xscale)
.ticks(11);
svg
.append("g")
.call(x_axis);
}
);
答案 0 :(得分:1)
根据您的评论,您要查找的是Point
比例而不是Linear
比例,并在数组中包含0
值。
您可以将years
数组直接用作domain
,然后点数比例将默认使用tickValues
的这些值。
$.getJSON(
"https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json",
function(x) {
var rawData = x.data;
var yearData = [];
var gdpData = [];
var width = 1020;
var height = 100;
for (var i = 0; i < rawData.length; i++) {
yearData.push(rawData[0][0]);
gdpData.push(rawData[1][1]);
}
//values which should be labeled on x-axis
var years = [0, // including the 0
1950,1955,1960,1965,1970,1980,1985,1990,2000,2005,2010,2015];
var svg = d3
.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
.append('g');
var xscale = d3
.scalePoint() // instead of Linear
.domain(years) // can use the years array directly as domain
.range([20,600]);
var x_axis = d3
.axisBottom()
.scale(xscale);
svg
.append("g")
.call(x_axis);
}
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.9.1/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>