【问题标题】:D3 - Map array to bar chartD3 - 将数组映射到条形图
【发布时间】:2020-10-01 04:56:16
【问题描述】:

我是 D3 的新手,并尝试通过以下示例实现一个简单的条形图: https://bl.ocks.org/caravinden/d04238c4c9770020ff6867ee92c7dac1

与原来的不同,我尝试将数组列表作为数据源。使用下面的代码会给我这些控制台错误:

错误:属性 y:预期长度,“NaN”。

错误:属性高度:预期长度,“NaN”。

图表本身不显示数据。 我知道在最后几行代码中设置 y 和 height 时会发生错误。如果我用数字替换 y(d.CasesTotal) 它工作正常(但显然根本没有意义)。 有什么想法吗?

var svg = d3.select("#barChart"),
    margin = {
        top: 20,
        right: 20,
        bottom: 30,
        left: 50
    },
    width = +svg.attr("width") - margin.left - margin.right,
    height = +svg.attr("height") - margin.top - margin.bottom,
    g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var x = d3.scaleBand()
    .rangeRound([0, width])
    .padding(0.1);
var y = d3.scaleLinear()
    .rangeRound([height, 0]);
console.log(y);
let fakeTimeline = [
    {StatDay: "a", CasesTotal: 500},
    {StatDay: "b", CasesTotal: 800}];
    //countryList[0].getFakeTimeLine();

x.domain(fakeTimeline.map(function(d) {return d.StatDay;}));
y.domain(0, d3.max(fakeTimeline, function(d) { console.log(d.CasesTotal);return Number(d.CasesTotal);}));
g.append("g")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x))

g.append("g")
    .call(d3.axisLeft(y))
    .append("text")
    .attr("fill", "#000")
    .attr("transform", "rotate(-90)")
    .attr("y", 6)
    .attr("dy", "0.71em")
    .attr("text-anchor", "end")
    .text("Fälle");

g.selectAll(".bar")
    .data(fakeTimeline)
    .enter().append("rect")
    .attr("class", "bar")
    .attr("x", function (d) {
        return x(d.StatDay);
    })
    .attr("width", x.bandwidth())
    .attr("y", function (d) {
        return y(d.CasesTotal);
    })
    .attr("height", function (d) {
        return height - y(d.CasesTotal);
    });

【问题讨论】:

  • D3 秤的域必须是数组。您使用 ([0,d3.max(...)]) 而不是 ([0,d3.max(...)]) 提供 Y 比例域。
  • 啊该死的,我没认出这个……现在可以了。谢谢!

标签: javascript d3.js


【解决方案1】:

D3 比例必须是一个数组。所以我改变了这个

y.domain(0, d3.max(fakeTimeline, function(d) { console.log(d.CasesTotal);return Number(d.CasesTotal);}));

到这里

y.domain([0, d3.max(fakeTimeline, function(d) { console.log(d.CasesTotal);return Number(d.CasesTotal);})]);

【讨论】:

    猜你喜欢
    • 2015-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-03
    • 2018-05-09
    • 2016-10-13
    • 1970-01-01
    相关资源
    最近更新 更多