gpt4 book ai didi

javascript - D3 负值直方图

转载 作者:行者123 更新时间:2023-11-29 18:19:28 24 4
gpt4 key购买 nike

我一直在学习本教程: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/但这仍然不起作用。

我做错了什么,我该如何支持负值?

谢谢

最佳答案

您的 width 函数出错了。您应该只将 svg 的宽度除以直方图中的 bin 数,以获得均匀宽度的条,填充整个图形。所以添加:

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/

关于javascript - D3 负值直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20184194/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com