简体   繁体   中英

D3.js chart with labels on both sides

D3.js beginner here. I have a horizontal stacked bar chart in D3 that only has 1 value in each bar (therefore, each bar is split into two values).

Like this:

val1 --------@@@@@@@@
val2 ----@@@@@@@@@@@@
val3 -----------@@@@@

Normally, D3 only supports a title for each bar, like above. What I'm looking for is to, instead of title, to write a label on the opposite ends of the bar. Like this:

val1 --------@@@@@@@@ valA
val2 ----@@@@@@@@@@@@ valB
val3 -----------@@@@@ valC

This could possibly be achieved by writing the text directly at the start of each bar, but if a bar is at 0%, then the text would overlap with the other 100% bar. Another option would be to align left/right, but I don't know how to do that either.

There is probably more than 1 way of doing this, hoping some D3 guru jumps in and gives me some pointers.

Maybe there's some way to custom draw labels on a typical chart? Then I could keep the left labels, and draw my custom ones to the right of each bar. I don't know what functions I would use for that.

Here's a sample graph that can be used to demonstrate the label feature. The graph is using the "wrong" orientation compared to what I'm asking, but I'll probably be able to adapt the answer:

https://www.d3-graph-gallery.com/graph/barplot_stacked_percent.html

Here's how you could add some labels to the top of the linked chart:

   svg.append('g') // add a new group
        .selectAll('text') // new empty selection
        .data(groups) // bind group names
        .enter() // add elements for new data
        .append('text') // text elements 
        .text(function(d) { return d}) // use the group names for the text
        .attr("x", function(d) { return x(d) + x.bandwidth()/2; }) // position the text in the middle of the appropriate bar
        .attr('y', -1) // raise the text slightly 
        .style('font-size', 10) 
        .style('text-anchor','middle')

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