我正在尝试将y轴刻度标签的左侧与y轴的右侧对齐。他们目前右对齐。
我试图通过选择所有文本元素并更改文本锚来解决此问题。这没有解决问题。
请参阅下面的代码以供参考。
document.addEventListener('DOMContentLoaded', () => {
var render = (selector, size, data) => {
var margin = size.margin;
var width = size.width - margin.left - margin.right;
var height = size.height - margin.top - margin.bottom;
var x = d3.scaleLinear()
.domain([-9,9])
.range([0, width]);
var xAxis = d3.axisBottom(x)
.ticks(19);
var y = d3.scaleBand()
.domain(data.map(d => d.name))
.rangeRound([0, height])
.padding(0.2);
var y2 = d3.scaleBand()
.domain(data.map(d => d.name2))
.rangeRound([0, height])
.padding(0.2);
var yAxis1 = d3.axisLeft(y)
.tickSize(0);
var yAxis2 = d3.axisRight(y2)
.tickSize(0)
.tickPadding(120);
var svg = d3.select(selector)
.attr('width', size.width)
.attr('height', size.height);
var chart = svg.append('g')
.attr('transform', `translate(${ margin.left }, ${ margin.top })`);
var bar = chart.selectAll('.bar')
.data(data)
.enter().append('rect')
.attr('class', d => `bar ${ d.value < 0 ? 'negative': 'positive' }`)
.attr('x', d => x(Math.min(0, d.value)))
.attr('y', d => y(d.name))
.attr('width', d => Math.abs(x(d.value) - x(0)))
.attr('height', y.bandwidth());
chart.append('g')
.attr('transform', `translate(0, ${ height })`)
.attr('class', 'axis x')
.call(xAxis);
chart.append('g')
.attr('class', 'axis y')
.attr('transform', `translate(${ x() }, 0)`)
.call(yAxis1);
// hope to left align y axis tick labels
chart.append('g')
.attr('class', 'axis y')
.attr("transform", "translate(" + 650 + ",0)")
.call(yAxis2)
.selectAll('text')
.style('text-anchor', 'left');
};
fetch('data.json')
.then(data => data.json())
.then(data => {
var settings = {
width: 1000,
height: 500,
margin: {
top: 20,
right: 200,
bottom: 30,
left:150
}
};
render('#chart', settings, data);
});
});