Hello I am currently trying to make a dynamic stacked barchart, with different career levels in ou community and a trend line according to each career level.
Ive managed to display the trendlines within the respective segment of the stacked barchart b simply adding the height below before doing my regression.
const data = {{ count_expertPerYearCareerLevel_db.data }};
// linear regression helper
function linearRegression(x, y) {
const n = x.length;
const sumX = x.reduce((a, b) => a + b, 0);
const sumY = y.reduce((a, b) => a + b, 0);
const sumXY = x.reduce((sum, xi, i) => {
return sum + xi * y[i];
}, 0);
const sumXX = x.reduce((sum, xi) => {
return sum + xi * xi;
}, 0);
const slope =
(n * sumXY - sumX * sumY) /
(n * sumXX - sumX * sumX);
const intercept =
(sumY - slope * sumX) / n;
return x.map(year => ({
year,
predicted: slope * year + intercept
}));
}
// ----- GROUP DATA -----
const grouped = {};
data.year.forEach((year, i) => {
const level = data.career_level[i];
if (!grouped[level]) {
grouped[level] = {
years: [],
counts: []
};
}
grouped[level].years.push(year);
grouped[level].counts.push(data.member_count[i]);
});
// automatic stack order
const stackOrder = Object.keys(grouped);
// ----- BUILD STACK BASES -----
const stackBase = {};
data.year.forEach((year, i) => {
const level = data.career_level[i];
const value = data.member_count[i];
if (!stackBase[year]) {
stackBase[year] = {};
}
stackBase[year][level] = value;
});
// ----- GENERATE TRENDLINES -----
const trendlines = [];
for (const level of stackOrder) {
const adjustedY = [];
const years = grouped[level].years;
years.forEach((year, idx) => {
let lowerStack = 0;
for (const lowerLevel of stackOrder) {
if (lowerLevel === level) break;
lowerStack +=
stackBase[year]?.[lowerLevel] || 0;
}
// center inside segment
const adjustedValue =
lowerStack +
(grouped[level].counts[idx] / 2);
adjustedY.push(adjustedValue);
});
// regression on adjusted positions
const result = linearRegression(
years,
adjustedY
);
result.forEach(r => {
trendlines.push({
career_level: level,
year: r.year,
trend: Number(r.predicted.toFixed(2))
});
});
}
return trendlines;
Now my issue is, that when I deselect a segment in my legend, the barchart accordingly shifts down but (obiously) the trendlines dont. I would like for them to again shift to the respective segment.
I treid to find out if theres an id of the legend items and if so let them influencethe calculation of the trendlines.
As well as rerunning the transformer(actually the query I reference at the top of the transformer) and use a js instead of a transformer to trigger it.
Currently Im at the end of my wits and would appreciate any help.
Thank you in advance!


