[英]Unable to get Text on Bar Chart in D3.js
I quite new to D3 and I am stuck with Text Issue in d3. 我对D3相当陌生,并且对d3中的Text Issue感到困惑。
Here is the D3 Code for a bar chart, I am simply unable to get text on the bars. 这是条形图的D3代码,我根本无法在条形图上获取文本。 The code for text is at the bottom.
文本代码在底部。 I am also attaching the picture for the chart.
我还附上图表图片。
<script type = "text/javascript">
var margin = { top: 80, bottom: 80, right: 80, left: 80 },
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.bottom + ")");
d3.tsv("tickets.tsv", function (error, data) {
dataset = data.map(function (d) { return [d["ticket"], +d["num"]]; })
var xScale = d3.scale.ordinal()
.domain(data.map(function (d) { return [d.ticket]; }))
.rangeRoundBands([0, width], 0.1);
var yScale = d3.scale.linear()
.domain([0, d3.max(data, function (d) { return Math.max([d.num]); })])
.range([height, 0]);
var rect = svg.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("x", function (d) { return xScale(d.ticket); })
.attr("y", function (d) { return yScale(d.num); })
.attr("height", function (d) { return height - yScale(d.num); })
.attr("width", xScale.rangeBand())
.attr("fill", "orange");
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left");
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(0" + "," + (height) + ")")
.call(xAxis);
svg.append("g")
.attr("class", "axis")
.call(yAxis);
var text = svg.selectAll("text")
.data(data)
.enter()
.append("text");
var labels = text
.attr("x", function (d) { return d.ticket; })
.attr("y", 400)
.text(function (d) { return d.num; });
;
});
</script>
</body>
</html>
It is because you are selecting based on text and there are already the tick text elements present...so, nothing to do off the .enter()
selection. 这是因为您正在基于文本进行选择,并且已经存在刻度文本元素...因此,无需执行
.enter()
选择。 So, select the text based on a class that you specify. 因此,请根据您指定的类选择文本。 Here is a FIDDLE with the simple solution.
这是具有简单解决方案的FIDDLE 。
var text = svg.selectAll(".text")
.data(data)
.enter()
.append("text")
.attr("class","text");
NOTE: I am using a javascript variable for the data but it is simple to adapt for you TSV data. 注意:我正在使用javascript变量作为数据,但是很容易适应您的TSV数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.