[英]d3.js histogram with positive and negative values
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. 我在这里使用了直方图示例http://bl.ocks.org/mbostock/3048450作为基础,虽然x轴值和刻度是正确的,但是这些条形图是午餐时间。
var values = [-15, -20, -22, -18, 2, 6, -26, -18, -15, -20, -22, -18, 2, 6, -26, -18];
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/ 检查这里的jfiddle: http : //jsfiddle.net/tNdJj/2/
I assume it's something missing from the "rect" creations but I am not seeing it. 我认为它是“rect”创作中缺少的东西,但我没有看到它。
Using the example of histogram from the following question: Bar chart with negative values 使用以下问题中的直方图示例: 带负值的条形图
I inversed x and y and adapted the display. 我反转了x和y并调整了显示。 Now you have a nice basis. 现在你有一个很好的基础。
Here is the corresponding jsFiddle: http://jsfiddle.net/chrisJamesC/tNdJj/4/ 这是相应的jsFiddle: http : //jsfiddle.net/chrisJamesC/tNdJj/4/
Here is the relevant code: 这是相关代码:
var data = [-15, -20, -22, -18, 2, 6, -26, -18];
var margin = {top: 30, right: 10, bottom: 10, left: 30},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var y0 = Math.max(Math.abs(d3.min(data)), Math.abs(d3.max(data)));
var y = d3.scale.linear()
.domain([-y0, y0])
.range([height,0])
.nice();
var x = d3.scale.ordinal()
.domain(d3.range(data.length))
.rangeRoundBands([0, width], .2);
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", function(d) { return d < 0 ? "bar negative" : "bar positive"; })
.attr("y", function(d) { return y(Math.max(0, d)); })
.attr("x", function(d, i) { return x(i); })
.attr("height", function(d) { return Math.abs(y(d) - y(0)); })
.attr("width", x.rangeBand());
svg.append("g")
.attr("class", "x axis")
.call(yAxis);
svg.append("g")
.attr("class", "y axis")
.append("line")
.attr("y1", y(0))
.attr("y2", y(0))
.attr("x1", 0)
.attr("x2", width);
Note: For simple visualizations like this, I would recommand using nvd3.js 注意:对于像这样的简单可视化,我建议使用nvd3.js
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); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.