我一直在制作一个基于子组的图表,如图所示:d3 bar chart with sub categories。
然而,数据点与y轴的比例有些不对劲。我原以为,无论域中的最大值是多少,图中数据点的高度都适合y轴上的相应值。当我运行时,虽然“250”在y轴上没有达到“250”标记。我误解了什么根本?谢谢你的帮助!
我的代码:
var margin = {top: 35, right: 200, bottom: 20, left: 80},
width = 960 - (margin.left + margin.right);
height = 400 - (margin.top + margin.bottom);
var svg = d3.select("#d3space").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var data=[250,250,250]; // a global
var data2=[data];
var coldomain=[];
console.log('data',data2);
var max=370
// X AXIS SECTION
var x = d3.scale.ordinal()
.domain([1])
.rangeRoundBands([0, width],0.08);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
// Y AXIS SECTION
var y = d3.scale.linear()
.domain([max,0])
.range([0,height]);
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
// READ LEGEND ITEMS INTO D3 DEFAULT ARRAY OF 20 COLOURS
var color = d3.scale.category10()
.domain(data);
svg.append("g") //"g" is DOM shorthand for a "group" object, which is a heuristic that lets you add things to everything in that group later
.attr("class", "xAxis")
.attr("transform", "translate(0," + height + ")") //this is responsible for moving axis from top (svg default) to bottom
.call(xAxis)
.append("text")
.attr("x", width+margin.left)
.attr("dy", ".71em")
.style("text-anchor", "end")
.style("font-size", "16px")
.attr("transform", "translate(40,0), rotate(0)")
.text("Month")
;
// Y AXIS TITLE
svg.append("g")
.attr("class", "yAxis")
.call(yAxis)
.append("text")
.attr("y", -17)
.attr("dy", ".71em")
.style("text-anchor", "middle")
.style("font-size", "16px")
.attr("transform", "translate(5,0), rotate(0)")
.text("Users")
;
var month = svg.selectAll('.grp')
.data(data2)
.enter()
.append('g')
// .attr("class", "g")
.attr('transform', function (d, i) {
console.log('i',i);
return 'translate(' + x(i) + ', 0)';
});
month.selectAll("rect")
.data(function(d) {
console.log('d',d);
return d; })
.enter().append("rect")
.attr("height", function(d) {
console.log('d',d);
return y(d); })
.attr("x", function(d,i) {
console.log('x',i,x.rangeBand(),(i)*(x.rangeBand()/5));
return (i)*(x.rangeBand()/5);})
.attr("y", function(d,i) {return height-y(d);})
.attr("width", 50)
.style("fill", function(d,i) {
console.log('col',color('A'));
return color(i); });
答案 0 :(得分:3)
您正在看到此行为,因为SVG y坐标位于页面顶部。也就是说,(0,0)是左上角,随着y坐标的增加,你正在向下移动页面。这对于条形显示的意义在于,您需要将y值的初始位置(y)和空间的剩余部分设置为x 0坐标,因为矩形向下延伸:
.attr("height", function(d) { return height-y(d); })
.attr("y", function(d,i) {return y(d);})
完成jsfiddle here。