D3分组图表之间的垂直线间距 [英] D3 vertical line beetween grouped chart bars spacing

查看:146
本文介绍了D3分组图表之间的垂直线间距的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:

组的数量是动态的,垂直线(分隔符)需要动态填充.使用 x0.rangeBand()获取组宽度.有没有办法动态获得两组之间的空间宽度?

The number of groups is dynamic, and vertical line (separator) needs dynamic padding. Group width im getting with x0.rangeBand(). Is there any way to get width of space beetween two groups dynamically?

代码和平:

.....

    var slice = svg.selectAll(".chart")
        .data(data)
        .enter().append("g")
        .attr("class", "g")
        .attr("transform", function (d) {
            return "translate(" + x0(d.category) + ",0)";
        });



    // Create rectangles of the correct width
    slice.selectAll("rect")
        .data(function (d) {
            return d.values;
        })
        .enter().append("rect")
        .attr("width", x1.rangeBand())
        .attr("x", function (d) {
            return x1(d.rate);
        })
        .style("fill", function (d) {
            return color(d.rate)
        })
        .attr("y", function (d) {
            return y(0);
        })
        .attr("height", function (d) {
            return height - y(0);
        })
        .on("mouseover", function (d) {
            d3.select(this).style("fill", d3.rgb(color(d.rate)).darker(2));
            tip.show(d);

        })
        .on("mouseout", function (d) {
            tip.hide
            d3.select(this).style("fill", color(d.rate));
        })

    slice.append("line")
        .attr("class", "blabla")
        .attr("x1", x0.rangeBand()+20)
        .attr("x2", x0.rangeBand()+20)
        .attr("y1", 0)
        .attr("y2", height + margin.top + margin.bottom)
        .style("stroke-width", 1)
        .style("stroke", "#000");
.....

这是几个小组的样子

这是许多团体的样子

This is how it looks with many groups

推荐答案

所以诀窍是重新计算填充自身. V3没有band.step()函数,因此我添加了此方法以获取两项的中间值:

So the trick is to recalculate padding self. V3 does not have band.step() function so I added this method to get the middle of two items:

function getMiddle(x0){

    var rng = x0.range();
    var band = x0.rangeBand();
    var padding = 0;

    if(rng.length>1){
        padding = (rng[1]-rng[0] - band) *0.5;
    }
    return band + padding;
}

和用法:

    slice.append("line")
        .attr("x1", getMiddle(x0))
        .attr("x2", getMiddle(x0))
        .attr("y1", 0)
        .attr("y2", height + margin.top + margin.bottom)
        .style("stroke-width", 1)
        .style("stroke", "#000");

这篇关于D3分组图表之间的垂直线间距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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