Preethi
Preethi

Reputation: 339

Text on horizontal bar chart - d3

I have a horizontal bar chart on which i'm displaying the field name. If the name(text) exceeds the bar , the text has to be in black color like in below. How would i do that?

Upvotes: 2

Views: 949

Answers (2)

cuckovic
cuckovic

Reputation: 2162

I've managed to do it using two text labels. Top label is wrapped in svg so it clips its length. Here is working example - http://jsfiddle.net/cuckovic/C6SSj/

bar.append("text")
    .attr("class", "below")
    .attr("x", 12)
    .attr("dy", "1.2em")
    .attr("text-anchor", "left")
    .text(function(d) { return d.sharedLabel; })
    .style("fill", "#000000");


bar.append("rect")
    .attr("class", "malebar")
    .attr("height", barWidth-gap)
    .attr("x", 10);



bar.append("svg")
    .attr({
        height: barWidth-gap
    })
    .append("text")
    .attr("class", "up")
    .attr("x", 12)
    .attr("dy", "1.2em")
    .attr("text-anchor", "left")
    .text(function(d) { return d.sharedLabel; })
    .style("fill", "#ffffff");

Upvotes: 2

Lars Kotthoff
Lars Kotthoff

Reputation: 109292

This is not a trivial thing to do. You would have to

  • Add the text.
  • Determine its actual dimensions using .getBBox() or something similar.
  • Remove the text.
  • Split the text into separate segments (e.g. tspans) depending on its actual width and the width of the bar.
  • Add those segments with the respective styles.

That is, you would have to manually break up the text into the parts that you want different styles for and then assign those styles.

Upvotes: 2

Related Questions