My goal is to create a horizontal stacked bar chart (1 bar) out of my data. The data looks like:
data = [{"Progress":20, "Value": 3}, {"Progress":80, "Value": 5}]
Where the X-Axis would be the Progress (its in %) from 0 to 100 in 10% steps. In the bar itself I would like then to give out the Value.
This is my Code where im stuck at. I have big problems to stack my Data the way I need it. Any help is welcome.
function drawChartStackedBar(data){
console.log(data);
var margin = {
top: 30,
right: 20,
bottom: 70,
left: 50
},
width = 600 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
// Adds the svg canvas
var svg = d3.select("#barChartHistogramm")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
// Create x and y scale.
var xScale = d3.scale.linear().range([0, width]);
var yScale = d3.scale.ordinal().range([0, height]);
// Create domains.
xScale.domain([0, 100]);
var xAxis = d3.svg.axis().scale(xScale)
.orient("bottom").ticks(6);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
// Create axes.
var x_axis = svg.append('g')
.attr('class', 'axis')
.attr('padding', 1)
.attr('transform', 'translate(' + 0 + ',' + height + ')')
.call(d3.svg.axis(xScale)
.ticks(1, 's'));
// Choose which columns to have as keys with slice method.
var keys = data.map(function(d) {
return d.Progress;
});
var newData = [{}];
data.forEach(function(d) {
newData[0][d.Progress] = d.Value
});
var stack = d3.layout.stack();
Create series of the data.
var series = stack(newData);
//Create color scale with colorbrewer or pass in array of colors.
var colorScale = d3.scale.ordinal()
.domain([0, 12])
.range(d3.schemeCategory10);
//Append rectangles.
var bars = svg.selectAll(null)
.data(data)
.enter()
.append('g')
.attr('fill', function(d) {
return colorScale(d.key);
})
.selectAll('rect')
.data(function(d) {
return d;
})
.enter()
.append('rect')
.attr('x', function(d, i) {
return xScale(d[0]);
})
.attr('width', function(d, i) {
return xScale(d[1]) - xScale(d[0]);
})
.attr("height", yScale.bandwidth());
console.log('function ended');
}
Im using D3Js v3.5