问题
I want to display the y-axis values of a nvd3 barchart on each individual bar. I can display the values, but I do not know how to set the height of the text element to be at the centre of each bar without hard coding the value. I use
d3.selectAll(".nv-bar")
to select each bar,but this does not have an height attribute ( as far as I can see). "discreteBar" has a height, but I cannot get in an d3.select()
I appreciate any help
<!DOCTYPE html>
<meta charset="utf-8">
<html>
<head>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.7.0/nv.d3.css">
</script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.7.0/nv.d3.css"
rel="stylesheet" type="text/css">
</head>
<body>
<div id="chartContainer" >
<script type="text/javascript">
var data = [
{ "Class":"One", "Value":500000 },
{ "Class":"Two", "Value":200000},
{ "Class":"Three", "Value":37000},
{ "Class":"Four", "Value":35000},
];
var nested_data = d3.nest()
.key(function (d) {undefined; })
.entries(data);
nv.addGraph(function() {
var width = 600, height = 600
var chart = nv.models.discreteBarChart()
.x(function (d) { return d.Class})
.y(function (d) { return d.Value})
.margin({ top: 30, right: 20, bottom: 50, left: 175 })
.tooltips(false)
.showValues(false)
.width(width)
.height(height)
.color(["#deebf7"])
.tooltipContent(function (key, x, y) {
return '<h3>' + x + '</h3>' +
'<p>'+ '£' + y + '</p>'
})
chart.yAxis
.tickFormat(d3.format(',.0f'));
d3.select('#chartContainer')
.append("svg")
.datum(nested_data)
.transition().duration(1000)
.call(chart);
d3.selectAll(".nv-bar")
.append("text")
.attr("x", chart.xAxis.rangeBand()/4)
.attr("y", 40)
.text(function (d) {
return d.Value
})
nv.utils.windowResize(chart.update);
return chart;
});
</script>
</div>
</body>
</html>
回答1:
Two things make this work.
First, you can't write the labels until the transition is over since the rects
won't have their proper height until then.
Second, you can get the rect height by using previousSibling
of the text you just added. Putting this together:
d3.select('#chartContainer')
.append("svg")
.attr('width', width)
.attr('height', height)
.datum(nested_data)
.transition().duration(1000)
.call(chart)
.each("end", function() {
d3.selectAll(".nv-bar")
.append("text")
.attr("x", chart.xAxis.rangeBand() / 4)
.attr("y", function(d) {
return d3.select(this.previousSibling).attr('height') / 2;
})
.text(function(d) {
return d.Value
})
});
Example here.
来源:https://stackoverflow.com/questions/28922042/how-to-correctly-centre-text-element-on-all-bars-of-a-nvd3-bar-chart