我是否可以使用D3绘制一个在一张图中有一条线的堆叠柱状图?
下面是一个例子:
任何帮助都是非常感谢的。
发布于 2015-12-21 10:51:08
为了实现您的可视化,我合并了以下内容:
制作天平和轴:
//x axis is ordinal
var x = d3.scale.ordinal()
.rangeRoundBands([0, width-150], .1);
//y left axis is linear for head count
var y = d3.scale.linear()
.rangeRound([height, 0]);
//this scale is for the average
y1 = d3.scale.linear().range([height, 0]).domain([0,100]);//marks can have min 0 and max 100
// y axis right for average marks.
var yAxisRight = d3.svg.axis().scale(y1)
.orient("right").ticks(5);
然后制作如下矩形和线状图(注释添加):
//filter out name and average
color.domain(d3.keys(data[0]).filter(function(key) { return key !== "Name" && key !=="Average"; }));
data.forEach(function(d) {
var y0 = 0;
d.group = color.domain().map(function(name) { return {name: name, y0: y0, y1: y0 += +d[name]}; });
d.total = d.group[d.group.length - 1].y1;
});
x.domain(data.map(function(d) { return d.Name; }));
//stores toltal headcount
y.domain([0, d3.max(data, function(d) { return d.total; })]);
//line function for averageLine
var averageline = d3.svg.line()
.x(function(d) { return x(d.Name) + x.rangeBand()/2; })
.y(function(d) { return y1(d.Average); });
//this will make the y axis to the right
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + (width-100) + " ,0)")
.style("fill", "red")
.call(yAxisRight);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Population");
var state = svg.selectAll(".state")
.data(data)
.enter().append("g")
.attr("class", "g")
.attr("transform", function(d) { return "translate(" + x(d.Name) + ",0)"; });
//adding the rect for group chart
state.selectAll("rect")
.data(function(d) { return d.group; })
.enter().append("rect")
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.y1); })
.attr("height", function(d) { return y(d.y0) - y(d.y1); })
.style("fill", function(d) { return color(d.name); });
svg.append("path") // Add the valueline path.
.attr("d", averageline(data));
//add the legend
var legend = svg.selectAll(".legend")
.data(color.domain().slice().reverse())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });
legend.append("rect")
.attr("x", width - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", color);
legend.append("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d) { return d; });
编辑
是的,你可以通过内插使直线弯曲:
var averageline = d3.svg.line()
.x(function(d) { return x(d.Name) + x.rangeBand()/2; })
.y(function(d) { return y1(d.Average); }).interpolate("basis");
读取这
工作代码这里
希望这能有所帮助!
https://stackoverflow.com/questions/34392913
复制相似问题