function gradientStackedBars(dataArray) {
const width = 800;
const height = 500;
const barWidth = 50;
const barSpacing = 100;
const svg = d3.create("svg")
.attr("width", width)
.attr("height", height);
const maxTotal = d3.max(dataArray, data => d3.sum(Object.values(data).filter(val => typeof val === 'number')));
const yScale = d3.scaleLinear()
.domain([0, maxTotal])
.range([height, 0]);
const xScale = d3.scaleBand()
.domain(dataArray.map((_, i) => i))
.range([0, width])
.padding(0.1);
dataArray.forEach((data, index) => {
if (index %2 !== 0){
const gradientId = `gradient${index}`;
const gradient = svg.append("defs")
.append("linearGradient")
.attr("id", gradientId)
.attr("x1", "0%")
.attr("y1", "100%")
.attr("x2", "0%")
.attr("y2", "0%");
let total = d3.sum(Object.values(data).filter(val => typeof val === 'number'));
let currentOffset = 0;
for (const [color, value] of Object.entries(data)) {
if (color !== 'date' && (value / total * 100) > 0) {
gradient.append("stop")
.attr("offset", `${currentOffset}%`)
.attr("stop-color", color);
currentOffset += (value / total * 100);
gradient.append("stop")
.attr("offset", `${currentOffset - 25}%`)
.attr("stop-color", color);
}
}
// Create bar with gradient fill
svg.append("rect")
.attr("x", xScale(index))
.attr("y", yScale(total)) // The y attribute will be set based on the total for that bar
.attr("width", xScale.bandwidth())
.attr("height", height - yScale(total)) // Height of the bar is determined by the difference from the SVG height
.style("fill", `url(#${gradientId})`);} else {// Define gradient
const gradientId = `gradient${index}`;
const gradient = svg.append("defs")
.append("linearGradient")
.attr("id", gradientId)
.attr("x1", "0%")
.attr("y1", "100%")
.attr("x2", "0%")
.attr("y2", "0%");
let total = d3.sum(Object.values(data).filter(val => typeof val === 'number'));
let currentOffset = 0;
for (const [color, value] of Object.entries(data)) {
if (color !== 'date' && (value / total * 100) > 0) {
gradient.append("stop")
.attr("offset", `${currentOffset}%`)
.attr("stop-color", color);
currentOffset += (value / total * 100);
gradient.append("stop")
.attr("offset", `${currentOffset}%`)
.attr("stop-color", color);
}
}
// Create bar with gradient fill
svg.append("rect")
.attr("x", xScale(index))
.attr("y", yScale(total)) // The y attribute will be set based on the total for that bar
.attr("width", xScale.bandwidth())
.attr("height", height - yScale(total)) // Height of the bar is determined by the difference from the SVG height
.style("fill", `url(#${gradientId})`);}
});
return svg.node();
}