d3.js带正负值的水平条形图-将y轴标签移动到图形的最左侧
在具有正值和负值的水平条形图上,y轴将位于页面中间的某个位置,我们如何将y轴标签移动到最左侧。以这个JSFIDLE为例,我们可以将foo、bar等从y轴移到图形的最左侧吗?d3.js带正负值的水平条形图-将y轴标签移动到图形的最左侧,d3.js,D3.js,在具有正值和负值的水平条形图上,y轴将位于页面中间的某个位置,我们如何将y轴标签移动到最左侧。以这个JSFIDLE为例,我们可以将foo、bar等从y轴移到图形的最左侧吗? //设定范围 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.do
//设定范围
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")
var y=d3.scaleBand()
.范围([高度,0])
.填充(0.1);
var x=d3.scaleLinear()
.范围([0,宽度]);
//缩放域中数据的范围
x、 域(d3)。范围(数据,函数(d){
返回d值;
}));
y、 域(data.map)(函数(d){
返回d.dataset;
}));
//为条形图添加矩形
svg.selectAll(“.bar”)
.数据(数据)
.enter().append(“rect”)
.attr(“类”,函数(d){
返回“条-条-”+(d.值<0?“负”:“正”);
})
.attr(“x”,函数(d){
返回x(数学最小值(0,d值));
})
.attr(“y”,函数(d){
返回y(d.dataset);
})
.attr(“宽度”,函数(d){
返回数学值abs(x(d.value)-x(0));
})
.attr(“高度”,y.带宽());
//添加x轴
svg.append(“g”)
.attr(“变换”、“平移(0)”、“高度+”)
.call(d3.axisBottom(x));
//添加y轴
svg.append(“g”)
.attr(“类”、“y轴”)
您可以通过手动移动刻度来实现:
// 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'})
//添加y轴
让yAxisGroup=svg.append(“g”)
.attr(“类”、“y轴”)
.attr(“转换”、“平移”(+x(0)+”,0)
.call(d3.axisRight(y));
yAxisGroup.selectAll(“.tick”)
.数据(数据)
.选择('文本')
.attr('x',函数(d,i){返回d.value您可以通过手动移动刻度来实现:
// 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'})
//添加y轴
让yAxisGroup=svg.append(“g”)
.attr(“类”、“y轴”)
.attr(“转换”、“平移”(+x(0)+”,0)
.call(d3.axisRight(y));
yAxisGroup.selectAll(“.tick”)
.数据(数据)
.选择('文本')
.attr('x',函数(d,i){返回d.value