时间:2015-07-23 17:12:42

标签: javascript d3.js

如何在分组条形图中的组之间添加一些填充?

我在x轴上有2组和5个类别。我试图在对之间得到一些填充([group1,group2,] space,[group1,group2]等)。我尝试使用rangeBand(),使用比例等,但它不起作用。

有什么建议吗?

jsfiddle

代码的相关样本:

var values = feature.properties;              
var data = [
    {name:"NoDipOL",value:values["NoDipOL"]},
    {name:"NoDipNOL",value:values["NoDipNOL"]},
    {name:"HSOL",value:values["HSOL"]},
    {name:"HSNOL",value:values["HSNOL"]},
    {name:"ColOL",value:values["ColOL"]},
    {name:"ColNOL",value:values["ColNOL"]},
    {name:"UnOL",value:values["UnOL"]},
    {name:"UnNOL",value:values["UnNOL"]}
];

var Colors =  ["#a6cee3", "#1f78b4"];
var ColorNames = ["Group1", "Group2"];

[...] 

// Scale for x and y axis
var x = d3.scale.ordinal()
    .domain(["No diploma", "High school", "College", "University"])
    .rangeRoundBands([0, width], .1);

var y = d3.scale.linear()
    .domain([0, d3.max(data, function(d){return d.value;})])
    .range([height, 0]);

//Ordinal x axis. 
var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom")
    .outerTickSize(0);

[...]

bar.append("rect")
    .attr("x", function(d, i) { return i * barWidth;})
    .attr("width", barWidth - 1 )
    .attr("y", function(d) {return y(d.value); })
    .attr("height", function(d) {return height - y(d.value);})
    .attr("fill", function(d, i) { return Colors[i % 2]; }); //Alternate colors

bar.append("text")
    .attr("class", "text")
    .text(function(d) { return d.value; })
    .attr("y", function(d) {return y(d.value) - 5; })
    .attr("x", function(d, i) { return i * barWidth;})
    .attr("dx", barWidth / 2)
    .attr("fill", "black")
    .attr("font-family", "sans-serif")
    .attr("font-size", "14px")
    .attr("text-anchor", "middle");

1 个答案:

答案 0 :(得分:2)

您可以使用rangeBand来放置刻度线,但不要使用它来调整和放置您的位置。首先修复数据,以便它可以使用rangeBand

var data = [
    {name:"No diploma",value:values["NoDipOL"]},
    {name:"No diploma",value:values["NoDipNOL"]},
    {name:"High school",value:values["HSOL"]},
    {name:"High school",value:values["HSNOL"]},
    {name:"College",value:values["ColOL"]},
    {name:"College",value:values["ColNOL"]},
    {name:"University",value:values["UnOL"]},
    {name:"University",value:values["UnNOL"]}
];

然后放置你的作品:

bar.append("rect")
    .attr("x", function(d, i) { 
        return (i % 2 === 0) ? // every other bar
            x(d.name) : // if even place at start of band
            x(d.name) + x.rangeBand()/2; // if odd (second bar) move it over
    })
    .attr("width", x.rangeBand()/2 )  // and width is half the rangeband
    ...

更新了example