1

I'm fairly new to d3.js and I'm building a bar graph in D3.js.

I'm trying to make the background three different colors to break the x axis into distinct three zones (low, medium, and high). I figure I should be appending some <g>elements but I'm not sure how to place them in this case.

The site is up here:

enter image description here

Not sure if providing more of the code would help

4

1 回答 1

0

这个答案是基于 Josh 在评论中建议的,但我想我会添加我的代码,因为我还必须处理鼠标悬停,所以这也带来了一些额外的挑战。

值得一提的是,SVG 没有 z-index,因此您必须先放入新的背景阴影,然后再制作图表条(这也是为什么您必须为条形图的矩形赋予新的名字,根据乔希的建议)

        svg.append("rect")
            .attr("y", padding)
            .attr("x", padding)
            .attr("width", 200)
            .attr("height", h -padding*2)
            .attr("fill", "rgba(0,255,0, 0.3")
            .attr("class", "legendBar")

        svg.append("rect")
            .attr("y", padding)
            .attr("x", padding +200)
            .attr("width", 200)
            .attr("height", h -padding*2)
            .attr("fill", "rgba(0,0,255, 0.3")
            .attr("class", "legendBar")

        svg.append("rect")
            .attr("y", padding)
            .attr("x", padding +400)
            .attr("width", 200)
            .attr("height", h -padding*2)
            .attr("fill", "rgba(255,0,0, 0.3")
            .attr("class", "legendBar")

        svg.selectAll("rect.bars")
            .data(dataset)
            .enter()
            .append("rect")
            .attr("class", "bars")
            .attr("x", 0 + padding)
            .attr("y", function(d, i){
                return yScale(i);
            })
            .attr("width", function(d) {
                return xScale(d.values[0]);
            })
            .attr("height", yScale.rangeBand())



.on("mouseover", function(d){

                var yPosition = parseFloat(d3.select(this).attr("y")) + yScale.rangeBand() /2
                var xPosition = parseFloat(d3.select(this).attr("x")) /2 + w /2;

                d3.select("#tooltip")
                    .style("left", "660px")
                    .style("top", "140px")
                    .select("#strat")
                    .text(d.values[3]);

                d3.select("#tooltip")
                    .select("#graph")
                    .attr("src", "img/cpg.jpg");

                d3.select("#tooltip")
                    .select("#studentName")
                    .text(d.name);

                d3.select("#tooltip").classed("hidden", false);
            })

            .on("mouseout", function() {
                d3.select("#tooltip").classed("hidden", true);
            });
于 2013-08-23T12:43:30.353 回答