d3.js具有正值和负值的直方图 [英] d3.js histogram with positive and negative values

查看:666
本文介绍了d3.js具有正值和负值的直方图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚如何正确创建一个直方图,其中数据数组中包含正值和负值。

I can't figure out how to properly create a histogram where there are both positive and negative values in the data array.

我使用了直方图示例这里 http://bl.ocks.org/mbostock/3048450 作为基准,而

I've used the histogram example here http://bl.ocks.org/mbostock/3048450 as a base, and while the x axis values and ticks are correct, the bars are out to lunch.

var values = [-15, -20, -22, -18, 2, 6, -26, -18, -15, -20, -22, -18, 2, 6, -26, -18];



X Scale



X Scale

var x0 = Math.max(-d3.min(values), d3.max(values));

var x = d3.scale.linear()
    .domain([-x0, x0])
    .range([0, width])
    .nice();

在这里检查jfiddle: http://jsfiddle.net/tNdJj/2/

Check the jfiddle here: http://jsfiddle.net/tNdJj/2/

我认为这是rect创作中缺少的东西但是我没有看到它。

I assume it's something missing from the "rect" creations but I am not seeing it.

推荐答案

诀窍是演示代码过于乐观,

The trick is that the demo code is overly optimistic, assuming that its input is positive:

bar.append("rect")
    .attr("x", 1)
    // .attr("width", x(data[0].dx) - 1)   // Does the wrong thing for negative buckets.
    .attr("width", x(data[0].x  + data[0].dx) - 1)
    .attr("height", function(d) { return height - y(d.y); });

http://jsfiddle.net/tNdJj/46/

这篇关于d3.js具有正值和负值的直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆