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

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

问题描述

我不知道如何正确创建直方图,其中数据数组中有正值和负值.

我在这里使用了直方图示例http://bl.ocks.org/mbostock/3048450 作为基础,虽然 x 轴值和刻度是正确的,但条形图已经出去吃午饭了.

数据

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

X 比例

var x0 = Math.max(-d3.min(values), d3.max(values));var x = d3.scale.linear().domain([-x0, x0]).range([0, 宽度]).好的();

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

我认为这是rect"中缺少的东西创作,但我没有看到.

解决方案

问题在于演示代码过于乐观,假设其输入为正:

bar.append("rect").attr("x", 1)//.attr("width", x(data[0].dx) - 1)//对负桶做错误的事情..attr("宽度", x(data[0].x + data[0].dx) - 1).attr("height", function(d) { return height - y(d.y); });

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

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

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.

Data

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

X Scale

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

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

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天全站免登陆