D3属性高度:预期长度,“NaN”

时间:2018-01-22 21:01:31

标签: javascript d3.js charts

可能是一个简单的错误,因为我是D3的新手,但我正在尝试创建一个带有缩放高度的简单条形图。它适用于硬编码高度,但返回错误“错误:属性高度:预期长度,”NaN“。”当我尝试使用线性刻度时。我已经登录了.d.grossbillions的类型,它是一个数字和我预期的数字,所以不知道为什么我得到NaN。非常感谢任何帮助。

HTML:

<h1>Top Grossing Films of 2017</h1>
<div class="chart"></div>

CSS:

<style type="text/css">
    svg {
        border:1px solid black;
        background-color: #e2ffff;
    }

    svg:nth-child(2){
        border:2px solid pink;
        fill: #00ff00;
    }

    text{
        fill: #fff;
        font-family: sans-serif;
        font-size: 1.1rem;
    }

    h1 {
        font-family: sans-serif;
    }
    body{
        text-align: center;
    }
</style>

使用Javascript:

<script type="text/javascript">
var gross = [
{name: 'The Last Jedi', grossBillions:1.7},
{name:'Fast and Furious 8', grossBillions:1.3},
{name:'Transformers: The Last Knight', grossBillions:1.2},
{name:'Despicable Me 3', grossBillions:1},
{name:'Beauty and The Beast', grossBillions:0.95},
{name:'Spider-Man Homecoming', grossBillions:0.9}
];

var yScale = d3.scaleLinear()
    .domain([0, d3.max(gross)])
    .range([0, 700]);

var chart = d3.select('.chart')
            .append('svg')
            .attr('width', gross.length*100)
            .attr('height', 700);

var bars = chart.selectAll('rect').data(gross);

 bars.enter()
    .append('rect')
        .attr('width', 50)
        .attr('height', function(d){return yScale(d.grossBillions) })
        .attr('class', 'bar')
        .attr('x', function(d,i) { return (i * 100)+20 })
        .attr('y', function(d){return 700 - d.grossBillions*400});

chart.selectAll( 'rect:nth-child(odd)' ).attr( 'fill' , '#494949' );
chart.selectAll( 'rect:nth-child(even)' ).attr( 'fill' , '#6b6b6b' );

var labels = chart.selectAll('text').data(gross);

labels.enter()
    .append('text')
    .text(function(d){return d.name + ' {$' + d.grossBillions + ' billion}'})
    .attr('y', 700)
    .attr('x', function(d,i) { return i * 100 });

chart.select('text:nth-child(7)').attr('transform', 'rotate(-90 10,660)');
chart.select('text:nth-child(8)').attr('transform', 'rotate(-90 110,660)');
chart.select('text:nth-child(9)').attr('transform', 'rotate(-90 210,660)');
chart.select('text:nth-child(10)').attr('transform', 'rotate(-90 310,660)');
chart.select('text:nth-child(11)').attr('transform', 'rotate(-90 410,660)');
chart.select('text:nth-child(12)').attr('transform', 'rotate(-90 510,660)');

1 个答案:

答案 0 :(得分:2)

yScale域的计算不正确,应该是:

var yScale = d3.scaleLinear()
  .domain([0, d3.max(gross, function(d){return d.grossBillions;}])
  .range([0, 700]);

这样,返回的值将被正确计算。