I'm trying to display the number of bars depending on the amount of rows i have in an array. Currently the numbers of bars displayed is determined by how many elements i have within an array. For example, [2,3,4,5], will display 4 stacked bars. But i want data = [[4, 8, 10], [50, 20, 20]] which gives me 2 stacked bars.
My code:
var margin = { top: 30, right: 30, bottom: 40, left: 50}
var data = [[4, 8, 10],
[50, 30, 20]
,[4, 18, 15],
[50, 20, 20]
];
var remapped = data.map(function(row) {
return row.map(function(col,i){
return { x: i, y: col };
});
});
var w = 200,
h = 200;
var svg = d3.select(".chart").append("svg:svg")
.attr("width", 4000)
.attr("height", 300 )
.append("svg:g")
.attr("transform", "translate(0,"+h+")");
var x = d3.scale.ordinal().rangeRoundBands([0, w], 0.4, 0.03)
var y = d3.scale.linear().range([0, h])
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]).domain(data[0].map(function(d,i){return i;}));
var chartContainer = svg.append('g').attr('class', 'bar-chart-container');
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; })]);
var group = chartContainer.selectAll("svg")
.data(stacked)
.enter().append("svg:g")
.attr("class", "group")
.style("fill", function(d, i) { return color(i); })
var rect = group.selectAll("rect")
.data(function(d){return d;})
.enter().append("svg:rect")
.attr("x", function(d, i) {; return x(d.x); })
.attr("y", function(d,i) { return -y(d.y0) - y(d.y); })
.attr("height", function(d) { return y(d.y); })
.attr("width", x.rangeBand());
Many thanks in advance for the time to read this.
Aucun commentaire:
Enregistrer un commentaire