D3 align text on left side of the axis from the right most character


D3 align text on left side of the axis from the right most character



So I have a D3 bar chart that looks like: bar chart. The problem appears for the smaller data bars when they overlap over the right side of the axis. I want to align the data text along the left side of the graph axis (as shown with the larger numbers) regardless of how small the bar is.


var data = [200.000001,3.00001,300.00001,1.00001,400.00001,5.0001,100.00001,20.0001,40.0001,50.00001, 2.00001];

//bar chart
var bars = d3.select("#chart").append("div").attr("class","chartstyle");
var b = bars.selectAll("div")
.data(data)
.enter().append("div")
.style("width", function(d) { return d + "px"; })
.text(function(d) { return d; });
});

//from stylesheet
<style>
.chartstyle div {
font: 10px;
background-color: red;
text-align: right;
padding: 0px;
margin: 0px;
color: black;
}
</style>




1 Answer
1



You'd better use svg:text elements with a text-anchor property set to end (see spec) instead of mixing nodes from different namespaces.


svg:text


text-anchor


end


var gBars = d3.select("#chart")
.selectAll(".bar-container")
.data(data)
.enter().append("g")
.attr("class", "bar-container");

// bars
gbars.append("rect")
.attr("class", "bar")
[...] // bars positioning and sizing logic

// labels
gBars.append("text")
.attr("class", "bar-label")
.attr("text-anchor", "end")
[...] // same positioning logic
.text(Object);





May the downvote be explained?
– Zim
2 days ago






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Export result set on Dbeaver to CSV

Opening a url is failing in Swift