Reputation: 351
How can I add label to a bar chart? The bar chart extends along the x-axis and I want to append the labels along the y-axis.
I read some examples and they use an external .tsv or .csv file. Can I store them in an array instead? My code is below :
var data = [7, 8, 15, 16];
var label = ["as","bs","cs","ds"];
var width = 420,
barHeight = 20;
var x = d3.scale.linear()
.domain([0, d3.max(data)])
.range([0, width]);
var chart = d3.select(".chart")
.attr("width", width)
.attr("height", barHeight * data.length);
var bar = chart.selectAll("g")
.data(data)
.enter().append("g")
.attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });
bar.append("rect")
.attr("width", x)
.attr("height", barHeight - 1);
bar.append("text")
.attr("x", function(d) { return x(d) - 3; })
.attr("y", barHeight / 2)
.attr("dy", ".35em")
.text(function(d) { return d; });
Upvotes: 1
Views: 4549
Reputation: 1983
You can get the value of your label by the index like this :
bar.append("text")
.attr("x", function(d) { return x(d) - 3; })
.attr("y", barHeight / 2)
.attr("dy", ".35em")
.text(function(d, i) { return label[i]; });
Upvotes: 1