如何将具有内核密度估计线的图表从d3.js版本3转换为d3.js版本4

时间:2017-11-30 14:35:45

标签: d3.js

我有一个带有核密度估计线的图表(用science.js创建)。目前,这里使用d3版本3,我需要将其转换为d3.js的版本4。

请帮助。

JSBin / Code Link:http://jsbin.com/nuzucibiju/edit?html,output



{{1}}




我正在尝试将d3.js v3转换为v4,但却遇到了很多错误。

如果将图表转换为所需的版本4将会很棒。

SourceCode

1 个答案:

答案 0 :(得分:1)

我建议你阅读this article。与d3v3相比,d3v4中直方图的变化是一个很好的解释。

您应该以这种方式重写代码:

var w = 952,
  h = 476,
  x = d3.scaleLinear().domain([30, 110]).range([0, w]),
  bins = d3.histogram().domain(x.domain()).thresholds(x.ticks(30))(data),
  max = d3.max(bins, function(d) { return d.y; }),
  y = d3.scaleLinear().domain([0, .1]).range([0, h]),
  yForHistogram = d3.scaleLinear()
  .domain([0, d3.max(bins, function(d) { return d.length; })])
  .range([h, 0]),
  kde = science.stats.kde().sample(data);

var vis = d3.select("body")
  .append("svg")
  .attr("width", w)
  .attr("height", h);

var bars = vis.selectAll("g.bar")
  .data(bins)
  .enter().append("g")
  .attr("class", "bar")
  .attr("transform", function(d) { return "translate(" + x(d.x0) + "," + yForHistogram(d.length) + ")"; });

bars.append("rect")
  .attr("fill", "steelblue")
  .attr("width", x(bins[0].x1) - x(bins[0].x0) - 1)
  .attr("height", function(d) {
    return h - yForHistogram(d.length);
  });
...

检查我提到的fork of JSBin。它适用于d3v4。