首先,让我们考虑两组数据的两个独立图表。秤是一样的。它看起来像这样:
http://jsfiddle.net/MmEjF/50/
好的。这一切都很好,但是我们如何从那里得到一个堆叠图表?
好吧,我们需要确保每个分时都有两条数据。
然后,在绘制每个刻度时,它应该从 0 开始绘制第一条数据,第二条数据不应该从零开始绘制,而是偏移第一个数据的数量。
考虑到这一点,其他部分就到位了:y 轴必须从 0 到两条数据之和的最大值。
var data = [{"year":2013,"month":3,"day":5,"count1":18, "count2":3},
{"year":2013,"month":3,"day":6,"count1":3, "count2":11},
{"year":2013,"month":3,"day":7,"count1":10,"count2": 8},
{"year":2013,"month":3,"day":8,"count1":18, "count2": 4}];
var maxValue = d3.max(data, function (d) {
return d.count1 + d.count2;
});
var yScale = d3.scale.linear()
.domain([0, maxValue])
.range([0, height]);
现在,更容易将每组条形图视为一个组,并将条形图添加到该组:
var bars = svg.selectAll(".bar")
.data(data).enter()
.append("g")
.attr("class","bar")
.attr("transform", function(d){
return "translate("+xTimeScale(d.date)+",0)"
});
var count1Bars = bars.append("rect")
.attr("class", "count1")
.attr("height", function(d){return yScale(d.count1)})
.attr("y", function(d){return height - yScale(d.count1)})
.attr("width", barWidth);
var count2Bars = bars.append("rect")
.attr("class", "count2")
.attr("height", function(d){return yScale(d.count2)})
.attr("y", function(d){return height - yScale(d.count1) -yScale(d.count2)})
.attr("width", barWidth);
var count1text = bars.append("text")
.text(function(d){return d.count1})
.attr("y", function(d){return height})
.attr("x", barWidth / 2);
var count2text = bars.append("text")
.text(function(d){return d.count2})
.attr("y", function(d){return height - yScale(d.count1)})
.attr("x", barWidth / 2);
现在,这只是一个让您上路的粗略示例:http: //jsfiddle.net/MmEjF/49/
祝你好运!想想你需要什么,事情往往会从那里落到实处!