D3从最右边的字符在轴的左侧对齐文本 [英] D3 align text on left side of the axis from the right most character
本文介绍了D3从最右边的字符在轴的左侧对齐文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有一个D3条形图,如下所示:条形图.当较小的数据条在轴的右侧重叠时,就会出现问题.我想使数据文本沿图形轴的左侧对齐(如较大的数字所示),而与条形的大小无关.
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>
推荐答案
最好将svg:text
元素的text-anchor
属性设置为end
(
You'd better use svg:text
elements with a text-anchor
property set to end
(see spec) instead of mixing nodes from different namespaces.
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);
这篇关于D3从最右边的字符在轴的左侧对齐文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文