我想在d3.js叠加条形图上显示y轴。 我可以显示x轴但我无法显示y轴。
这是我的代码,但y轴从不显示。 我确实犯了一个错误,但我看不到。
var w = 600,
h = 500
var dataset = [
{"month":"JAN","purchased":6,"sold":3},
{"month":"FEV","purchased":7,"sold":5},
{"month":"MARS","purchased":4,"sold":3},
{"month":"AVR","purchased":4,"sold":2},
{"month":"MAI","purchased":8,"sold":1},
{"month":"JUIN","purchased":3,"sold":3},
{"month":"JUIL","purchased":3,"sold":4},
{"month":"AOU","purchased":4,"sold":2},
{"month":"SEPT","purchased":6,"sold":3},
{"month":"OCT","purchased":6,"sold":4},
{"month":"NOV","purchased":7,"sold":3},
{"month":"DEC","purchased":6,"sold":3}
];
var matrix = new Array();
$.each(dataset, function(i, item) {
var oneMonth = new Array();
oneMonth.push(dataset[i].month);
oneMonth.push(dataset[i].purchased);
oneMonth.push(dataset[i].sold);
matrix.push(oneMonth);
});
var remapped =["purchased","sold"].map(function(dat,i){
return matrix.map(function(d,ii){
return {x: ii, y: d[i+1] };
})
});
var x = d3.scale.ordinal()
.domain(dataset.map(function (d) {return d.month; }))
.rangeRoundBands([ 0, w ], .4);
var y = d3.scale.linear()
.domain([0, 15])
.range([0, h-50]);
var z = d3.scale.ordinal().range(["#e01b5d", "#eda13e"]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
// create canvas
var svg = d3.select("#viz").append("svg:svg")
.attr("class", "chart")
.attr("width", w)
.attr("height", h )
.append("svg:g")
.attr("transform", "translate(10,470)")
.call(xAxis);
var stacked = d3.layout.stack()(remapped);
x.domain(stacked[0].map(function(d) { return d.x; }));
y.domain([0, d3.max(stacked[stacked.length - 1], function(d) { return d.y0 + d.y; })]);
// Add a group for each column.
var valgroup = svg.selectAll("g.valgroup")
.data(stacked)
.enter().append("svg:g")
.attr("class", "valgroup")
.style("fill", function(d, i) { return z(i); });
// Add a rect for each date.
var rect = valgroup.selectAll("rect")
.data(function(d){return d;})
.enter().append("svg:rect")
.attr("x", function(d) { return x(d.x); })
.attr("y", function(d) { return -y(d.y0) - y(d.y); })
.attr("height", function(d) { return y(d.y); })
.attr("width", x.rangeBand());
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(20)")
.call(yAxis);
结果如下
感谢您的帮助