大家好我正在使用d3和堆叠条,我的垂直版本有堆叠条(工作正常),我想在水平条中转换...
我的垂直功能就是这样做..
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], 0.3);
var y = d3.scale.linear()
.rangeRound([height, 0]);
var dataIntermediate = options.map(function(item){
return datos.map(function(d){
if (item in d)
return {x:d.label, y:d[item]};
else
return{x:d.label, y:0};
});
});
var dataStackLayout = d3.layout.stack()(dataIntermediate);
x.domain(dataStackLayout[0].map(function (d) {
return d.x;
}));
y.domain([0,
d3.max(dataStackLayout[dataStackLayout.length - 1],
function (d) {
return d.y0 + d.y;
})
])
.nice();
var layer = svg.selectAll(".stack")
.data(dataStackLayout)
.enter().append("g")
.attr("class", "stack")
.style("fill", function (d, i) {
return color(i);
});
layer.selectAll("rect")
.data(function (d) {return d; })
.enter().append("rect")
.attr("x", function (d) {
return x(d.x);
})
.attr("y", function (d) {
return y(d.y + d.y0);
})
.attr("height", function (d) {
return y(d.y0) - y(d.y + d.y0);
})
.attr("width", x.rangeBand())
.on("mousemove", function(d){
div.style("left", d3.event.pageX+10+"px");
div.style("top", d3.event.pageY-25+"px");
div.style("display", "inline-block");
div.html((d.x)+"<br>"+"Code"+": "+(d.code)+"<br>"+"Value"+": "+(d.y));
})
.on("mouseout", function(d){
div.style("display", "none");
});
在我的横向版本中,我更改了x
的所有y
和x0
的{{1}}并更改了我的尺度
y0
但是不要工作......任何想法
答案 0 :(得分:1)
我认为你有正确的想法,交换x代表y(并按照你的记录修改比例),但可能还有一些其他步骤,例如宽度和高度的几个关键变化。
一个简单的说明是y坐标从height
开始并向上运行(到零)。使用x坐标,从零开始并逐步完成(到width
)。因此,如果您只是将x换成y,您将获得一个从右侧开始的水平条形图(这可能是合乎需要的)。
更重要的是,在你的例子中:
.attr("y", function (d) {
return y(d.y + d.y0);
})
.attr("height", function (d) {
return y(d.y0) - y(d.y + d.y0);
})
起始y属性看起来不错,但是height属性不应该依赖于数据值,它应该等于y.bandwidth()。
同样适用于x:
.attr("x", function (d) {
return x(d.x);
})
.attr("width", x.rangeBand())
水平堆叠条的每个部分的宽度应取决于数据值。这可以通过交换attr&#34; height&#34;来解决。为&#34;宽度&#34;反之亦然。
我在两个方向之间建立了bl.ocks.org的比较(它是基于Mike Bostock的一个块的水平条形图,但评论显示了原始内容每一行)。可在此处找到:https://bl.ocks.org/andrew-reid/0aedd5f3fb8b099e3e10690bd38bd458