D3 -如何正确标记x轴

D3 - how to label x Axis correctly

本文关键字:何正确 D3      更新时间:2023-09-26

我的目标是用1960年到2080年的年份标记x轴,每隔10步。我有一个。csv文件,看起来像这样:

Land,1960,1970,1980,1990,2000,2010,2020,2030,2040,2050,2060,2070,2080
Belgien,9128824,9660154,9855110,9947782,10239085,10839905,11824225,12885338,13918014,14758714,15400272,16027593,16614305

到目前为止,我得到了这个结果(见图)

结果图片

我不知道如何正确标记x轴。下面是我到目前为止的代码:

d3.csv("/Data/temp_eu_popul.csv", function(e, eu_popul) {
console.log(eu_popul);

var years = [1960,1970,1980,1990,2000,2010,2020,2030,2040,2050,2060,2070,2080];
    console.log(years);
var population = [];
  for(var i = 1960; i<=2080; i+= 10){
    population.push(parseFloat(eu_popul[0][i]));
  }
console.log(population);
var svg = d3.select("body")
  .append("svg")
    .attr("width", 500)
    .attr("height", 500);
var y = d3.scaleLinear()
  .domain(d3.extent(population))
  .range([250, -50]);
var x = d3.scaleLinear()
  .domain([0,years.length])
  .range([100, 450]);
var yAxis = d3.axisLeft(y);
    svg.append('g')
        .attr("transform", "translate(75,150)")
        .attr('class', 'y axis')
        .call(yAxis);
var xAxis = d3.axisBottom(x);
svg.append('g')
  .attr("transform", "translate(0,450)")
  .attr('class', 'x axis')
  .call(xAxis);
var circles = svg.selectAll("cirle").data(population).enter().append("circle")
.attr("cx", function(d,i){ return x(i); })
.attr("cy", function(d,i){ return 350-y(d); })
    .attr("r", 2);
});

我想要做的就是改变:

var x = d3.scaleLinear()
  .domain(d3.extent(years))
  .range([100, 450]);
var circles = svg.selectAll("cirle").data(population).enter().append("circle")
.attr("cx", years)
.attr("cy", function(d,i){ return 350-y(d); })
    .attr("r", 2);
});

另一件事是,我创建了一个额外的数组。但我打赌有更好的办法来解决这个问题。因为年份已经在csv文件中了。我能在不创建额外数组的情况下使用它们吗?

在您的情况下,您的x轴比例可以被认为是一个序数比例,因此您需要使用

x = d3.scaleOrdinal().domain(years).range([min, max])

,其中min和Max是您自己的x范围值,它将您的确切年份映射到像素x值。

对于"cx"调用,您应该使用.attr('cx', function(d) {return x(d)})

或者更简洁地说,.attr('cx', x)

是d3的缩写

您的circles变量中也有拼写错误,您选择了所有"圆圈"!

另外,我认为你的csv数据最好是垂直格式,而不是水平格式:

Land, Belgien 1960, 9128824

等。

,然后你可以访问属性d.Landd.Belgien,无论你想要相应的数字影响你的标记,从一个匿名的function(d,i){}定义,你可以构造你的年数组,例如,通过使用

var years = eu_popul.map(function(d) {return d.Land});

试试这个:

var x = d3.scaleLinear()
  .domain(d3.extent(years)) // or .domain(d3.extent(eu_popul[1]))
  .range([100, 450]);
var xAxis = d3.axisBottom(x);
svg.append('g')
  .attr("transform", "translate(0,450)")
  .attr('class', 'x axis')
  .call(xAxis); 
var circles = svg.selectAll("circle").data(population).enter().append("circle")
.attr("cx", function(d,i){ return x(years[i]); })
.attr("cy", function(d,i){ return 350-y(d); })
    .attr("r", 2);
});