Barchart의 막대 위에 값을 표시합니다
-
21-12-2019 - |
문제
X 축에 대한 서수 스케일이있는 막대 차트가 있습니다.각 막대의 맨 또는 각 막대의 아래쪽에 y 값을 표시하고 싶습니다.바를 통해 하나의 호버를 가리킬 때 y 값을 표시하는 것이 허용됩니다.DC.js에서는 함수가 있거나 그렇게 할 수있는 방법이 있습니까?다음은 JSFiddle 이고 내 코드는 그림>
아래에 있습니다.편집 : 여기에 내 코드가 있습니다. html
<body>
<div id='Chart'>
</div>
</body>
.
JS
var data = [{
Category: "A",
ID: "1"
}, {
Category: "A",
ID: "1"
}, {
Category: "A",
ID: "1"
}, {
Category: "A",
ID: "2"
}, {
Category: "A",
ID: "2"
}, {
Category: "B",
ID: "1"
}, {
Category: "B",
ID: "1"
}, {
Category: "B",
ID: "1"
}, {
Category: "B",
ID: "2"
}, {
Category: "B",
ID: "3"
}, {
Category: "B",
ID: "3"
}, {
Category: "B",
ID: "3"
}, {
Category: "B",
ID: "4"
}, {
Category: "C",
ID: "1"
}, {
Category: "C",
ID: "2"
}, {
Category: "C",
ID: "3"
}, {
Category: "C",
ID: "4"
}, {
Category: "C",
ID: "4"
},{
Category: "C",
ID: "5"
}];
var ndx = crossfilter(data);
var XDimension = ndx.dimension(function (d) {
return d.Category;
});
var YDimension = XDimension.group().reduceCount(function (d) {
return d.value;
});
dc.barChart("#Chart")
.width(480).height(300)
.dimension(XDimension)
.group(YDimension)
.transitionDuration(500)
.xUnits(dc.units.ordinal)
.label(function(d) {return d.value})
.x(d3.scale.ordinal().domain(XDimension))
dc.renderAll();
. 해결책
업데이트 된 jsfiddle
.renderlet(function(chart){
var barsData = [];
var bars = chart.selectAll('.bar').each(function(d) { barsData.push(d); });
//Remove old values (if found)
d3.select(bars[0][0].parentNode).select('#inline-labels').remove();
//Create group for labels
var gLabels = d3.select(bars[0][0].parentNode).append('g').attr('id','inline-labels');
for (var i = bars[0].length - 1; i >= 0; i--) {
var b = bars[0][i];
//Only create label if bar height is tall enough
if (+b.getAttribute('height') < 18) continue;
gLabels
.append("text")
.text(barsData[i].data.value)
.attr('x', +b.getAttribute('x') + (b.getAttribute('width')/2) )
.attr('y', +b.getAttribute('y') + 15)
.attr('text-anchor', 'middle')
.attr('fill', 'white');
}
})
.
바를 다시 촬영할 때 라벨이 보이지 않게 원하지 않으면 (예를 들어 사용자는 사용자 필터를 클릭하면 다른 차트를 클릭하면) de renderlet에서 이전 값의 검사를 preredraw 청취자.
.on("preRedraw", function(chart){
//Remove old values (if found)
chart.select('#inline-labels').remove();
})
.
대안
d3-ish way
demo jsfiddle
.renderlet(function (chart) {
//Check if labels exist
var gLabels = chart.select(".labels");
if (gLabels.empty()){
gLabels = chart.select(".chart-body").append('g').classed('labels', true);
}
var gLabelsData = gLabels.selectAll("text").data(chart.selectAll(".bar")[0]);
gLabelsData.exit().remove(); //Remove unused elements
gLabelsData.enter().append("text") //Add new elements
gLabelsData
.attr('text-anchor', 'middle')
.attr('fill', 'white')
.text(function(d){
return d3.select(d).data()[0].data.value
})
.attr('x', function(d){
return +d.getAttribute('x') + (d.getAttribute('width')/2);
})
.attr('y', function(d){ return +d.getAttribute('y') + 15; })
.attr('style', function(d){
if (+d.getAttribute('height') < 18) return "display:none";
});
})
. 다른 팁
dc.js 버전 3. *..renderLabel(true)
를 사용할 수 있습니다.그것은 맨 위로 가치를 인쇄합니다
renderlet
메소드를 사용하는 Hacky 솔루션이 있습니다. jsfiddle > http://jsfiddle.net/tpsc5f9f/4/ / P>
js
var barChart = dc.barChart("#Chart")
.width(480).height(300)
.dimension(XDimension)
.group(YDimension)
.transitionDuration(500)
.xUnits(dc.units.ordinal)
.x(d3.scale.ordinal().domain(XDimension))
dc.renderAll();
barChart.renderlet(function(chart){
moveGroupNames();
});
function moveGroupNames() {
var $chart = $('#Chart'),
bar = $chart.find('.bar');
bar.each(function (i, item) {
var bar_top = this.height.baseVal.value;
var bar_left = this.width.baseVal.value;
var bar_offset_x = 30;
var bar_offset_y = 33;
var bar_val = $(this).find('title').html().split(':')[1];
$chart.append('<div class="val" style="bottom:'+(bar_top+bar_offset_y)+'px;left:'+((bar_left*i)+(bar_offset_x))+'px;width:'+bar_left+'px">'+bar_val+'</div>');
});
}
.
첨가 된 CSS
body {
margin-top:20px;
}
#Chart {
position:relative;
}
#Chart .val {
position:absolute;
left:0;
bottom:0;
text-align: center;
}
. 전문화 된 Valueaccessor를 차트로 사용하는 경우 Dimirc의 "D3-Ish Way"솔루션으로 다음 대체를 할 수 있습니다.
변경
.text(function(d){
return d3.select(d).data()[0].data.value
})
.
~
.text(function(d){
return chart.valueAccessor()(d3.select(d).data()[0].data)
});
. 이 함수는 행 차트의 레이블을 각 행의 끝까지 위치를 변경합니다."Y"속성을 사용하여 막대 차트에 비슷한 기술을 사용할 수 있습니다.
- 차트의 전이 를 사용하여 행 RECT와 함께 행렬과 함께 애니메이션
- 는 차트의 ValueAcessor 기능을 사용합니다
- 는 차트의 Xaxis 스케일을 사용하여 레이블 위치를 계산합니다
rowChart.on('pretransition', function(chart) {
var padding = 2;
chart.selectAll('g.row > text') //find all row labels
.attr('x', padding) //move labels to starting position
.transition() //start transition
.duration(chart.transitionDuration()) //use chart's transitionDuration so labels animate with rows
.attr('x', function(d){ //set label final position
var dataValue = chart.valueAccessor()(d); //use chart's value accessor as basis for row label position
var scaledValue = chart.xAxis().scale()(dataValue); //convert numeric value to row width
return scaledValue+padding; //return scaled value to set label position
});
});
.
제휴하지 않습니다 StackOverflow