D3.js覆盖条形图显示错误

时间:2015-07-15 08:27:10

标签: javascript d3.js

我正在尝试制作如下图像:graph

但由于条形图正在重叠,我无法正确添加轴。

我的代码如下:

<script type="text/javascript">
var birth_years = [];
var count_birth = [];
for(i = 0; i<json_final.length; i++) {
    birth_years.push(json_final[i].birth_year);
    count_birth.push(json_final[i].count);
}
var ages = [] //age is the data
for (var i = 0; i < birth_years.length; i++) {
    //count_birth is the number of people whose birth date is indicated by birth_year
    ages.push({"age": new Date().getFullYear() - birth_years[i], "number_of_people": count_birth[i]});
}

console.log(ages);

var results,
    chart,
    bars,
    margin = 100,
    w = 8,
    h = 500,
    x, y,
    xAxis, yAxis;

results = d3.map(ages);


chart = d3.select('body')
        .append('svg')
        .attr('class', 'chart')
        .attr('width', 100)
        .attr('height', h)
        .append('g')


d3.select('svg g')
    .attr('transform', 'translate(50, 50)');

x = d3.scale.linear()
    .domain([10,80])
    .rangeRound(0, 550),

 y = d3.scale.linear()
    .domain( [0, d3.max( ages, function( d ) { return d.number_of_people; } )] )
    .rangeRound( [0, h - margin] );



// Bars
bars = chart.append('g')
    .attr('class', 'bars');
 bars.selectAll( 'rect' )
    .data( ages )
        .enter()
        .append('rect')
        .attr('x', function( d, i ) { return d.age  } )
    .attr( 'y', function( d ) { return (h - margin) - y( d.number_of_people )} )
    .attr( 'width', w )
    .attr( 'height', function( d ) { return y( d.number_of_people ) } )
    .append('g');
//console.log(t);



// Axis - I get some errors when I tried to use this
xAxis = d3.svg.axis()
    .scale(x)
    .ticks(20)
    .orient('bottom')
    .tickSize(6, 3, 1);

yAxis = d3.svg.axis()
    .scale(d3.scale.linear().domain( [0, d3.max( ages, function( d ) { return d.number_of_people; } )] ).rangeRound( [h - margin, 0] ))
    .tickSize(6, 3, 1)
    .orient('left');

到目前为止我得到的图片基本上就是这个:

My graph

如果有人帮助我,我们将非常感激。

谢谢!

0 个答案:

没有答案