본문 바로가기

엉터리 개발 이야기/Superset

[Superset] Bar Chart -Stacked 설정 했을 경우 Legend 클릭 시 Bar Value 변경하기

반응형


Bar Chart에서 Stacked 설정을 했을 경우

Legend 클릭 시 총합이 변하지 않아 기능 추가

smallRect 찾는 부분 개선 필요. 한번 읽으면서 Y가 작은걸 넣어주면 된다...아직 실력 부족

const addTotalBarValues1 = function (svg, chart, data, stacked, axisFormat) {

const format = d3.format(axisFormat || '.3s');

const totalStackedValues = stacked && data.length !== 0 ?
data[0].values.map(function (bar, iBar) {
const bars = data.map(function (series) {
return series.values[iBar];
});
return d3.sum(bars, function (d, idx) {
if(chart.state.disabled[idx] === false) return d.y;
});
}) : [];

if(!svg.select('g.nv-barsWrap').selectAll('text.bar-chart-label').empty()) {
svg.select('g.nv-barsWrap').selectAll('text.bar-chart-label').remove();
}

const groupLabels = svg.select('g.nv-barsWrap').append('g');

const valueCount = data[0].values.length;
const seriesCount = data.length;

let smallYRect = [];
let smallY = 10000;
for(var i=0; i<valueCount; i++) {
for(var j=0; j<seriesCount; j++) {
let seriesObj = svg.selectAll('g.nv-group')[0][j];

if(seriesObj.childNodes.length != 0) {
let childNode = seriesObj.childNodes[i];
if(smallY >= childNode.y.baseVal.value) {
smallYRect[i] = childNode;
smallY = childNode.y.baseVal.value;
}
}
}
smallY = 10000;
}


smallYRect.forEach(function(d, index) {
//if(d.classList.contains('positive')) {
let attrs = d.attributes;

const transformAttr = attrs.transform.value;
const yPos = parseFloat(attrs.y.value);
const xPos = parseFloat(attrs.x.value);
const rectWidth = parseFloat(attrs.width.value);

const t = groupLabels.append('text')
.attr('x', xPos) // rough position first, fine tune later
.attr('y', yPos - 5)
.text(format(stacked ? totalStackedValues[index] : d.y))
.attr('transform', transformAttr)
.attr('class', 'bar-chart-label');
const labelWidth = t.node().getBBox().width;
t.attr('x', xPos + rectWidth / 2 - labelWidth / 2); // fine tune
//}
});


};


let smallYRect = [];
svg.select('g.nv-groups').selectAll('g.nv-group').each( function (d, i) {
d3.select(this).selectAll('rect').each(function(d1, i1) {
d3.select(this).select(function () {
if(i === 0) {
smallYRect[i1] = this;
} else {
if(smallYRect[i1].y.baseVal.value > this.y.baseVal.value) {
smallYRect[i1] = this;
}
}
});
});
}); //smallYRect 찾는 것 개선


if(fd.show_legend) {
chart.legend.margin({top: 10, right: 0, left: 0, bottom: 30});
}

chart.legend.dispatch.on('legendClick', function(series, index) {
if (fd.show_bar_value) {
if(fd.bar_stacked) {
setTimeout(function () {
addTotalBarValues1(svg, chart, data, stacked, fd.y_axis_format, series.key);
}, animationTime);
}
}
});


반응형