所以我在D3的条形图的x轴上使用了序数刻度,我已经将其移动,使得刻度位于各自条形的中心之下。由于某些类别的名称有些冗长,我选择旋转文本标签并将文本锚点设置为结尾。但是,旋转文本字段会使轴的对齐变得混乱。所以我很好奇是否有办法获得水平x刻度位置,这样我就可以将文本字段位置映射到相应的刻度位置,并获得完美居中的旋转文本标签。
请参阅以下小提琴(SO允许的代码更长)
https://jsfiddle.net/SumNeuron/fzk6eyy2/
{{1}}
或者,在此处查看代码:
https://bl.ocks.org/SumNeuron/7989abb1749fc70b39f7b1e8dd192248
和演示:
https://bl.ocks.org/SumNeuron/raw/7989abb1749fc70b39f7b1e8dd192248/
答案 0 :(得分:1)
您可以在获得文字的相同选项中设置x
和y
位置以及text-anchor
样式:
d3_selection.selectAll("text")
.attr("y", 0)
.attr("x", 0)
.style("text-anchor", "end")
.attr("transform","rotate(-45)")
以下是演示:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3-array.v0.7.min.js"></script>
<script src="https://d3js.org/d3-collection.v0.1.min.js"></script>
<script src="https://d3js.org/d3-color.v0.4.min.js"></script>
<script src="https://d3js.org/d3-format.v0.5.min.js"></script>
<script src="https://d3js.org/d3-interpolate.v0.5.min.js"></script>
<script src="https://d3js.org/d3-scale.v0.6.min.js"></script>
<script src="https://d3js.org/d3-selection.v0.6.min.js"></script>
<script src="https://d3js.org/d3-axis.v0.2.min.js"></script>
<script src="https://d3js.org/d3-array.v0.6.min.js"></script>
<style>
line, path, .domain, .bar {
stroke: black;
fill: none;
}
text{
fill: black;
}
</style>
</head>
<body>
<script>
var margin = {top: 20, right: 10, bottom: 110, left: 10};
var width = 500;
var height = 400;
var chartWidth = 500 - margin.left - margin.right;
var chartHeight = 400 - margin.top - margin.bottom;
var axisHeight = 30;
var data = [
{key:'Long text', value: 1},
{key:'Text', value: 3},
{key:'Long long text', value: 2},
{key:'Text', value: 3},
{key:'Some long long text', value: 4},
];
var scaleX = d3_scale.scaleBand()
.domain(data.map(function(d){ return d.key; }))
.range([0, chartWidth])
.paddingInner([0.1])
.paddingOuter([0.3])
.align([0.5]);
var scaleY = d3_scale.scaleLinear()
.domain([0, d3_array.max(data.map(function(d){ return d.value; }))])
.range([0, chartHeight]);
var axis = d3_axis.axisBottom(scaleX)
.tickSizeInner(4)
.tickSizeOuter(20)
.tickPadding(3);
var panel = d3_selection.select("body").append("svg")
.attr("class", "axis")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate("+[margin.left, margin.top]+")")
panel.attr("transform", "translate("+[margin.left, height - margin.bottom]+")")
.call(axis);
panel.selectAll('rect.bar')
.data(data)
.enter().append('rect')
.attr("class", "bar")
.attr("width", scaleX.bandwidth())
.attr("height", function(d){ return scaleY(d.value); })
.attr("x", function(d){ return scaleX(d.key); })
.attr("y", function(d){ return -scaleY(d.value); })
d3_selection.selectAll("text").attr("y", 0)
.attr("x", 0)
.style("text-anchor", "end")
.attr("transform","rotate(-45)")
</script>
</body>