D3具有负值的直方图

时间:2013-11-25 03:21:14

标签: javascript d3.js histogram

我一直在关注本教程:http://www.youtube.com/watch?v=cu-I2um024k,我正在尝试使用数据点数组创建直方图。当数据点都是正值时,我的代码工作正常:http://jsfiddle.net/sbeleidy/yDBQU/

var data = [1,2,3,4,5,6,9,12,23,5,4,1,2,30,24,21,18,19,41,43,36,38,5,52,1,23,1,2,5,3,1,2,4,4,21,2,3,4,1,2,5,7,8,5,3,1,10,12,24,4,21,34,35,35,35,35,36,37,32,1,31,32,32,23,23,24,25,27,45,46,47,0];

        var width = 500,
            height = 500,
            padding = 50;

        var histogram = d3.layout.histogram()
            .bins(data.length/3)
            (data);

        console.log(histogram);


        var someArray =[];
        for (var i=0; i < histogram.length; i++){
            someArray.push(histogram[i].length);
        }
        var maxVal = d3.max(someArray);

        var y = d3.scale.linear()
            .domain([0, maxVal])
            .range([0,height]);

        var x = d3.scale.linear()
            .domain([d3.min(data),d3.max(data)])
            .range([0,width])

        var xAxis = d3.svg.axis()
            .scale(x)
            .orient('bottom');

        var canvas = d3.select('body').append('svg')
            .attr('width',width)
            .attr('height',height + padding)

        var xAxisPrinter = canvas.append('g')
            .attr('transform','translate(0,'+height+')')
            .call(xAxis);

        var bars = canvas.selectAll('.bar')
            .data(histogram)
            .enter()
            .append('g')

        bars.append("rect")
            .attr('x', function(d){return x(d.x);})
            .attr('y', function(d){return height - y(d.y);})
            .attr('width', function(d){return x(d.dx); })
            .attr('height', function(d){return y(d.y);})
            .attr('fill','steelblue')

        bars.append('text')
            .attr('x', function(d){return x(d.x); })
            .attr('y', function(d){return height - y(d.y);})
            .attr('dx',function(d){return x(d.dx)/2;})
            .attr('dy',"20px")
            .attr('text-anchor','middle')
            .text(function(d){
                if (d.y != 0){
                    return d.y;
                }
                else {
                    return null;
                }})

但是当我在数据中添加一些负值时,我会得到非常奇怪的数据宽度(参见http://jsfiddle.net/sbeleidy/K5EW7/

我尝试了答案:d3.js histogram with positive and negative values并执行了此操作:http://jsfiddle.net/sbeleidy/M23ks/ 但那还是不行。

我做错了什么以及如何支持负值?

由于

1 个答案:

答案 0 :(得分:4)

你的宽度函数正在抛弃它。您应该将svg的宽度除以直方图中的二进制数,以获得均匀的宽度条,填充整个图形。所以添加:

var numbins = histogram.length;

然后:

bars.append("rect")
    .attr('x', function(d){return x(d.x);})
    .attr('y', function(d){return height - y(d.y);})
    .attr('width', width/numbins)
    .attr('height', function(d){return y(d.y);})
    .attr('fill','steelblue')

或者您可以将条形宽度定义为变量:

var barwidth = width/numbins;

然后将其作为宽度值传递。

请看这里的工作代码:

http://jsfiddle.net/M23ks/2/