Reputation: 21
May be a simple mistake as I'm super new to D3 but I'm trying to create a simple bar chart with a scaled height for the bars. It works fine with hard coded heights but returns the error "Error: attribute height: Expected length, "NaN"." when I try to use a linear scale. I've console.logged the typeof for d.grossbillions and it is a number and the numbers I expected so not sure why I'm getting NaN. Any help is much appreciated.
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)');
Upvotes: 2
Views: 1362
Reputation: 1182
The computation of your yScale
domain is incorrect, it should be something like:
var yScale = d3.scaleLinear()
.domain([0, d3.max(gross, function(d){return d.grossBillions;}])
.range([0, 700]);
This way, the returned value will be computed correctly.
Upvotes: 2