Reputation: 639
Is there a way to display values above the bars in this graph? I have the values being retrieved from a TSV, but am currently having difficulty getting the bar values to be displayed as labels above each respective bar.
This is the data that I have as TSV:
This is what I currently have for rendering the graph:
margin =
top: 30
right: 30
bottom: 40
left: 60
width = 960 - margin.left - margin.right
height = 500 - margin.top - margin.bottom
formatPercent = d3.format("")
x = d3.scale.ordinal()
.rangeRoundBands([width, 0], .1)
y = d3.scale.linear()
.range([height, 0])
xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickFormat(formatPercent)
yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(formatPercent)
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.top + ")")
d3.tsv("/Home/GetTsv/data.tsv", (error, data)->
data.forEach((d)->
d.Total = +d.Total
)
x.domain(data.map((d)-> d.Year))
y.domain([0, d3.max(data, (d)-> d.Total)])
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.append("text")
.attr("y", 30)
.attr("x", width / 2)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Year")
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", -60)
.attr("x", -(height / 2))
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Total Activity")
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", (d)-> x(d.Year))
.attr("width", x.rangeBand())
.attr("y", (d)-> y(d.Total))
.attr("height", (d)-> height - y(d.Total))
# svg.selectAll("text")
# .data(data)
# .enter()
# .append("text")
# .text((d)-> d.Total)
# .attr("x", (d, i)-> i * (width / data.length))
# .attr("y", (d)-> height - d)
)
This is what my graph looks like:
But I would like to have labels above the bars, similar to this:
The code that is commented-out is my attempt at trying to make the value labels show above the bars.
Upvotes: 3
Views: 2789
Reputation: 1522
Pasting this code in the text section should do the trick:
.attr("text-anchor", "middle")
.attr("x", function(d, i) { return i * (width / dataset.length) + (width / dataset.length) / 2; })
.attr("y", function(d) { return height - (d * 10) - 10; })
the -10 there makes some distance from the bar, in this case 10px obviously. also the other numbers are to be tweaked a bit, i just pasted the code from a file i had so i don't know exactly what it would look like on your code since i don't have the dataset to try. If it doesn't can you paste the script in http://jsfiddle.net/ so I can try and work it out? Let me know how it works out!
Upvotes: 4