在D3中:
我使用“年龄”列创建了具有多列数组,“年龄”和“性别”的直方图。我的直方图仅使用“年龄”数据。但是我希望能够将相应的“性别”数据存储在直方图中或存储在容器中。这样我可以计算一些关于当我将鼠标悬停在那个垃圾箱时处理垃圾箱的“性别”数据的事情 - 再次,该垃圾箱(以及整个直方图)建立在“年龄”数据上。
示例数据:
{
"age":[22,21,30,26,28,26,23,32,30,26,34,23,33,23,34,28,34,35,31,15,26,34,32,21,35,28,27,26,24,19,21,32,23,23,23,23,28,32,22,26,32,21,25,30,23,30,21,20,28,28,26,26,31,39,25,30,36,23,38,30,30,31,23,22,28,26,23,32,26,34,28,30,24,27,26,38,24,30,34,25,28,35,22,27,26,25,29,32,26,30,33,33,31,31,37,28,27,28,29,16],
"gender":["1","0","0","0","1","1","1","1","1","1","0","1","0","0","1","0","0","0","1","1","1","1","0","0","1","0","1","0","0","1","0","0","1","0","0","1","1","0","1","1","0","1","0","0","1","1","0","0","1","0","1","1","1","0","1","1","1","0","1","1","0","1","0","1","1","1","1","1","0","1","1","0","1","0","1","1","1","1","0","0","1","0","1","1","0","0","1","1","0","1","1","1","0","1","1","0","0","1","1","0"]
}
以下是一些代码。我认为这一切都与此问题直接对应,但如果需要更多信息,请告诉我:
var histogram = d3.layout.histogram()
.frequency(false)
.bins(x.ticks(10));
var canvas = 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 + ")");
d3.json("100sample.json", function(error, data) {
//var allData = histogram(allAge.age);
var allAge = histogram(data.age);
var allBars = canvas.selectAll(".allBar")
.data(allAge)
.enter().insert("rect", ".axis")
.attr("class", "allBar")
.attr("x", function(d) { return x(d.x) + 1; })
.attr("y", function(d) { return y(d.y); })
.attr("width", x(allAge[0].dx + allAge[0].x) - x(allAge[0].x) - 1)
.attr("height", function(d) { return height - y(d.y); })
.on('mouseover', allTip.show)
.on('mouseout', allTip.hide);
我使用“鼠标悬停”并构建直方图等等。每个年龄值都有相应的性别值,但性别值不会更改条形码/直方图。我当时认为将性别价值添加到
中有所作为.data()
但不知何故没有在直方图布局上调用它们?
如何合并与直方图所用数据相对应的额外数据?
---更新----
我知道有必要将整个数据集绑定到svg / canvas allBars变量,以便我可以访问allAge以获取我尝试在鼠标悬停时计算的元数据的直方图和性别。
我有:
var total = [allAge, data.gender];
从data.age创建allAge直方图后。这可能不是一次引入所有数据的最佳方式......
现在,而不是:
.data(allAge)
我有:
.data(total)
所以我需要在直方图构造上索引total [0],在与鼠标悬停关联的元数据上索引total [1]。如何在allbars var中进行索引 - 特别是在.attr中构建直方图?
答案 0 :(得分:1)
你真的很亲密!
您想要的是致电.data(data)
来绑定您的所有数据,而不仅仅是年龄。这将使数据可用于最后与.on
绑定的回调。那你为什么要过allAge
?好吧,因为那是你从histogram
函数中得到的回报。 <{3}}状态
返回值是一个数组数组:外部数组中的每个元素表示一个bin,每个bin包含来自输入值的关联元素。
好 - 所以你不要通过直方图功能运行它来丢失数据。但是它不会因为在对象中有两个数组而感到困惑吗?这就是docs函数的用武之地。将它链接到您定义histogram
的位置。对于回调,您可能会使用function(d){return d.age}
,或者您可能需要使用数组长度2并按索引进行操作。您也可以尝试accessor数组。
我认为您不需要修改.attr
次来电,因为它们会对垃圾箱进行操作,而不是对其中的数据进行操作。我还建议再看看你如何设置宽度 - 再次,你必须摆弄它,但也许function(d){return x(d.dx) -1}
会更好。即使dx
应该相同,直接访问数据也是一个红旗。
希望这有帮助。如果我完全没有基础(因为我没有为你编写代码),请告诉我。