在具有正值和负值的水平条形图上,y轴位于页面中间某处,我们如何将y轴标签移动到最左侧。以这个jsfiddle为例,我们可以将foo,bar等从y轴移动到图形的最左侧吗?
https://jsfiddle.net/Kavitha_2817/fmr1x1gu/18/
var margin = {top: 30, right: 10, bottom: 50, left: 50},
width = 500,
height = 300;
var data = [{value: -10, dataset:"barbaz"},
{value: 40, dataset:"barbar"},
{value: -10, dataset:"foobaz"},
{value: -50, dataset:"foobar"},
{value: 30, dataset:"baz"},
{value: -20, dataset:"bar"},
{value: -70, dataset:"foo"}];
// Add svg to
var svg = d3.select('body').append('svg').attr('width', width +
margin.left + margin.right).attr('height', height + margin.top +
margin.bottom).append('g').attr('transform', 'translate(' + margin.left
+ ',' + margin.top + ')');
//设置范围
var y = d3.scaleBand()
.range([height, 0])
.padding(0.1);
var x = d3.scaleLinear()
.range([0, width]);
// Scale the range of the data in the domains
x.domain(d3.extent(data, function (d) {
return d.value;
}));
y.domain(data.map(function (d) {
return d.dataset;
}));
// append the rectangles for the bar chart
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", function (d) {
return "bar bar--" + (d.value < 0 ? "negative" : "positive");
})
.attr("x", function (d) {
return x(Math.min(0, d.value));
})
.attr("y", function (d) {
return y(d.dataset);
})
.attr("width", function (d) {
return Math.abs(x(d.value) - x(0));
})
.attr("height", y.bandwidth());
// add the x Axis
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
// add the y Axis
svg.append("g")
.attr("class", "y axis")
答案 0 :(得分:1)
您可以通过手动移动刻度来实现:
// add the y Axis
let yAxisGroup = svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + x(0) + ",0)")
.call(d3.axisRight(y));
yAxisGroup.selectAll('.tick')
.data(data)
.select('text')
.attr('x', function(d,i){return d.value<0?9:-9})
.style('text-anchor', function(d,i){return d.value<0?'start':'end'})