[英]Flip the x-axis of a D3 Stacked Bar Chart
Chapter 11 of " Interactive Data Visualization for the Web " shows how to create stacked bar charts with the D3.js library . “ Web交互式数据可视化 ”的第11章介绍了如何使用D3.js库创建堆叠的条形图。 The example produces an upside down chart with the bars attached to the top of the x-axis. 该示例生成了一个上下颠倒的图表,其中的条形图连接到x轴的顶部。
Flipping the chart and attaching them to the bottom is left as an exercise for the reader. 翻转图表并将其附加到底部作为练习。
Given this starting point: 给定这个起点:
<script src="http://d3js.org/d3.v3.min.js"></script>
<script type="text/javascript">
var w = 500;
var h = 300;
var dataset = [[ { x: 0, y: 5 }, { x: 1, y: 4 }, { x: 2, y: 2 }, { x: 3, y: 7 }, { x: 4, y: 23 }],
[ { x: 0, y: 10 }, { x: 1, y: 12 }, { x: 2, y: 19 }, { x: 3, y: 23 }, { x: 4, y: 17 } ],
[ { x: 0, y: 22 }, { x: 1, y: 28 }, { x: 2, y: 32 }, { x: 3, y: 35 }, { x: 4, y: 43 } ]];
var stack = d3.layout.stack();
stack(dataset);
var xScale = d3.scale.ordinal()
.domain(d3.range(dataset[0].length)).rangeRoundBands([0, w], 0.05);
var yScale = d3.scale.linear()
.domain([0, d3.max(dataset, function(d) {
return d3.max(d, function(d) { return d.y0 + d.y; });
})])
.range([0, h]);
var colors = d3.scale.category10();
var svg = d3.select("body").append("svg").attr("width", w).attr("height", h);
var groups = svg.selectAll("g").data(dataset).enter().append("g")
.style("fill", function(d, i) { return colors(i); });
var rects = groups.selectAll("rect")
.data(function(d) { return d; })
.enter()
.append("rect")
.attr("x", function(d, i) { return xScale(i); })
.attr("y", function(d) { return yScale(d.y0); })
.attr("height", function(d) { return yScale(d.y); })
.attr("width", xScale.rangeBand());
</script>
What needs to be done to flip the chart? 翻转图表需要做什么?
The solution I came up with involves three changes: 我提出的解决方案涉及三个更改:
Change the yScale .range from: 从以下位置更改yScale .range:
.range([0, h]);
to: 至:
.range([h, 0]);
Change the rect "y" .attr from: 将rect“ y” .attr更改为:
.attr("y", function(d) { return yScale(d.y0); })
to: 至:
.attr("y", function(d) { return yScale(d.y0) + yScale(dy) - h; })
Change the rect "height" .attr from: 从以下位置更改rect“ height” .attr:
.attr("height", function(d) { return yScale(dy); })
to: 至:
.attr("height", function(d) { return h - yScale(dy); })
With those changes applied, the stacks attach to the bottom and still maintain their relative sizes. 应用这些更改后,堆栈将附着在底部,并且仍保持其相对大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.