简体   繁体   中英

d3 y axis label position

I have a grouped bar chart design that has each bar amount immediately above the bar instead of the y axis bar on the far left.

I have added the text like so...

svg.selectAll(".text")
.data(data)
.enter()
.append("text")
.attr("class","label")
  .attr("x", function(d) { return x1(d.rate) })
  //.attr("y", function(d) { return y(d.value) + 1; })
.attr("dy", ".75em")
.text(function(d) {return d.value; });

But i cant seem to obtain the x and y values according to the bar position and the actual text of the d.value isn't getting inserted.

Sample here: https://jsfiddle.net/6p7hmef1/7/

That's because the data bound to the texts that you're adding isn't right.

If you add a console.log as follows, you'll be able to see why the labels aren't being inserted. Check for the outputs in console. Console log fiddle

.text(function(d) {console.log(d); return d.value; });

One approach would be to append the texts to the bar groups ("slice" in your case). Just like you do for the bars. Here's a fiddle doing this: JS Fiddle Demo

    slice.selectAll(".text")
    .data(function(d) { return d.values; })
    .enter()
    .append("text")
    .attr("class","label");
  slice.selectAll('text.label')
    .attr("x", function(d) { return x1(d.rate)+ x1.rangeBand()/3 })
    .attr("y", function(d) { return y(d.value) + 1; }).attr('dy', '-0.4em')
    .text(function(d) {return d.value; });

This might look weird as the texts are shown before the transition of the bars. So changing the value of texts once the bars are shown seems like the right approach to me. (dx and dy attributes can be adjusted as per the requirement)

Here's the final fiddle : JS FIDDLE

I'm using the "end" callback for every transition and changing the text values accordingly.

.each('end', function () {
    d3.select(this.parentNode).selectAll('text.label')
        .attr("x", function(d) { return x1(d.rate)+ x1.rangeBand()/3 })
        .attr("y", function(d) { return y(d.value) + 1; }).attr('dy', '-0.4em')
        .text(function(d) {return d.value; });
})

Hope this helps. :) Let me know if any part of the code isn't understandable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM