axis doesn't show first and last item?

174 views
Skip to first unread message

Rob Dodson

unread,
Apr 3, 2012, 12:32:14 AM4/3/12
to d3...@googlegroups.com
I'm working on my first d3 visualization, a really simple bar chart of projected human population from 1950 - 2049. http://bl.ocks.org/2289263

I've almost got it all working but my horizontal axis doesn't seem to show the first and last of its ticks (1950 and 2049). It also doesn't quite meet the vertical axis. My vertical axis is mostly correct but it doesn't show the highest value. Any help is GREATLY appreciated.

Thank you!

- rob

Jason Davies

unread,
Apr 4, 2012, 6:06:19 AM4/4/12
to d3...@googlegroups.com

Firstly, you aren't parsing the date correctly:

result.year = new Date(parseInt( val.Year, 10 ), 1, 1);

The month is zero-based i.e. it runs from 0 to 11, so this should be:

result.year = new Date(parseInt( val.Year, 10 ), 0, 1);

Alternatively, you can use D3's built-in date formatting/parsing:

var parseYear = d3.time.format("%Y");
// …
result.year = parseYear.parse(val.Year);

Shorter and less error-prone. :)

Secondly, your x-scale domain should extend all the way to the last year
*plus* one, because the last datum extends all the way to the end of
that year. So you want something like this:

.domain( [data[0].year, d3.time.year.offset(data[data.length - 1].year, 1)] )

Lastly, the last bar appears a bit too wide. This is because the
x-scale range appears to be incorrect, and the bars are overlapping each
previous bar but not the last one. The x-scale range should be:

.range( [0, w * data.length] )

In addition, the translation of the vertical axis is a bit off, it
should be:

.attr('transform', 'translate(' + x.range()[1] + ')')

You also have a small white gap at the bottom of the bars, which you can
get rid off using a .5-pixel offset:

.attr( 'y', function( d ) { return (h - margin) - y( d.population ) + .5 } )

You might be better off showing more ticks on the y-axis. You can also
try using .nice() on the y-scale to extend the scale to the next "nice"
round value.

Here's my version with the aforementioned changes:

http://bl.ocks.org/2300078

--
Jason Davies, http://www.jasondavies.com/

Rob Dodson

unread,
May 1, 2012, 12:08:08 AM5/1/12
to d3...@googlegroups.com
Thank you for the thorough response Jason. I'm just now getting back into D3 for my new project. This is super helpful!
Reply all
Reply to author
Forward
0 new messages