d3中的钢筋位置与轴不匹配 [英] Bar position in d3 is not matching with axis
问题描述
我有一个使用d3js
制作的条形图,其中我无法沿x轴正确放置这些条形.条形相对于轴抽线的位置不正确.
I've a bar chart made using d3js
where I'm unable to position the bars properly along the x-axis. The bars are not positioned relative to the axis tics.
以下是同一段代码.
var width = 216;
var height = 200;
var barPadding = 18;
var barWidth = 58;
var dataSize = d3.selectAll(dataset).size();
var margin = { top: 10, right: 0, bottom: 58, left: 30 };
var width_box_sizing_border_box = width + margin.left + margin.right;
var height_box_sizing_border_box = height + margin.bottom + margin.top;
//var start = (width - margin.left - margin.right - (dataSize * barWidth) + barPadding) / 2;
var graph;
var xScale;
var yScale;
var dataset;
var xTicks = 6;
var yTicks = 6;
dataset = [{ desc: 'test1', val: 40 }, { desc: 'some dummy text here', val: 120 }];
xScale = d3.scaleBand()
.domain(dataset.map(function (d) {
return d.desc;
}))
.range([margin.left, width-margin.right]);
yScale = d3.scaleLinear()
.range([height, 0])
.domain([0, 350]);
graph = d3.select("#graph")
.append("svg")
.attr("class", "bar-chart")
.attr("width", width_box_sizing_border_box)
.attr("height", height_box_sizing_border_box)
graph.append("g")
.attr("class", "x-scale")
.attr("transform", "translate(0," + (height + margin.top) + ")")
.call(d3.axisBottom(xScale).ticks(xTicks))
.selectAll(".tick text")
.call(wrap, xScale.bandwidth());
graph.append("g")
.attr("class", "y-scale")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(d3.axisLeft(yScale).ticks(yTicks).tickPadding(10));
graph
.append("g")
.attr("transform", "translate(0," + margin.top + ")")
.attr('class', 'graph-placeholder')
.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("class", "bar1")
.attr("height", height)
.attr("width", barWidth - barPadding)
.attr('x', d => xScale(d.desc));
graph
.append("g")
.attr("transform", "translate(0," + margin.top + ")")
.attr('class', 'graph-main')
.selectAll("bar1")
.data(dataset)
.enter()
.append("rect")
.attr("class", "bar2")
.attr('x', d => xScale(d.desc))
.attr("y", function (d) {
return yScale(d.val);
})
.attr("height", function (d) {
return height - yScale(d.val);
})
.attr("width", barWidth - barPadding);
graph
.append("g")
.attr("transform", "translate(0," + margin.top + ")")
.attr('class', 'bar-label')
.selectAll("text")
.data(dataset)
.enter()
.append("text")
.text(d => d.val + '%')
.attr('x', d => xScale(d.desc))
.attr("y", function (d) {
return yScale(d.val) - 5;
})
function wrap(text, width) {
text.each(function () {
var text = d3.select(this),
words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1,
y = text.attr("y"),
dy = parseFloat(text.attr("dy")),
tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
}
}
});
}
.bar-chart {
background-color: #ccc;
}
.bar2 {
fill: steelblue;
}
.bar1 {
fill: #f2f2f2;
}
text {
font-size: 12px;
text-anchor: middle;
}
.bar-label text {
text-anchor: start;
}
path.domain {
stroke-width: 0;
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div class="container">
<div id="graph"></div>
</div>
推荐答案
以下是计算中心点以放置条形/文本的方法
Here's how you can compute the center point to place the bars/texts
条形文字:
xScale.bandwidth()/2 - barWidth/2
文本的其他偏移量,以使文本在条中居中:
分配了text属性后,请根据barWidth和此特定的文本宽度放置文本(即x
).
Additional offset for the texts to center them within the bars:
Once the text attribute is assigned, position the text (i.e. x
) based on the barWidth and this particular text width.
简而言之:barWidth/2 - textWidth/2
,为此,您可以使用 getBBox 方法.方法如下:
In short terms: barWidth/2 - textWidth/2
and to do that you can use the getBBox method. Here's how:
.attr('x', function (d) {
return xScale(d.desc) + ((barWidth - barPadding)/2 - d3.select(this).node().getBBox().width/2);
});
将以上2项更改应用于图表,这是您的小提琴(和内联代码段)的一个分支
Applying the above 2 changes to your chart, here's a fork of your fiddle (and an inline snippet)
var width = 216;
var height = 200;
var barPadding = 18;
var barWidth = 58;
var dataSize = d3.selectAll(dataset).size();
var margin = { top: 10, right: 0, bottom: 58, left: 30 };
var width_box_sizing_border_box = width + margin.left + margin.right;
var height_box_sizing_border_box = height + margin.bottom + margin.top;
//var start = (width - margin.left - margin.right - (dataSize * barWidth) + barPadding) / 2;
var graph;
var xScale;
var yScale;
var dataset;
var xTicks = 6;
var yTicks = 6;
dataset = [{ desc: 'test1', val: 40 }, { desc: 'some dummy text here', val: 120 }];
xScale = d3.scaleBand()
.domain(dataset.map(function (d) {
return d.desc;
}))
.range([margin.left, width-margin.right]);
yScale = d3.scaleLinear()
.range([height, 0])
.domain([0, 350]);
graph = d3.select("#graph")
.append("svg")
.attr("class", "bar-chart")
.attr("width", width_box_sizing_border_box)
.attr("height", height_box_sizing_border_box)
graph.append("g")
.attr("class", "x-scale")
.attr("transform", "translate(0," + (height + margin.top) + ")")
.call(d3.axisBottom(xScale).ticks(xTicks))
.selectAll(".tick text")
.call(wrap, xScale.bandwidth());
graph.append("g")
.attr("class", "y-scale")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(d3.axisLeft(yScale).ticks(yTicks).tickPadding(10));
graph
.append("g")
.attr("transform", "translate(" + (xScale.bandwidth()/2 - (barWidth - barPadding)/2) + "," + margin.top + ")")
.attr('class', 'graph-placeholder')
.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("class", "bar1")
.attr("height", height)
.attr("width", barWidth - barPadding)
.attr('x', d => xScale(d.desc));
graph
.append("g")
.attr("transform", "translate(" + (xScale.bandwidth()/2 - (barWidth - barPadding)/2) + "," + margin.top + ")")
.attr('class', 'graph-main')
.selectAll("bar1")
.data(dataset)
.enter()
.append("rect")
.attr("class", "bar2")
.attr('x', d => xScale(d.desc))
.attr("y", function (d) {
return yScale(d.val);
})
.attr("height", function (d) {
return height - yScale(d.val);
})
.attr("width", barWidth - barPadding);
graph
.append("g")
.attr("transform", "translate(" + (xScale.bandwidth()/2 - (barWidth - barPadding)/2) + "," + margin.top + ")")
.attr('class', 'bar-label')
.selectAll("text")
.data(dataset)
.enter()
.append("text")
.text(d => d.val + '%')
.attr("y", function (d) {
return yScale(d.val) - 5;
}).attr('x', function (d) {
return xScale(d.desc) + ((barWidth - barPadding)/2 - d3.select(this).node().getBBox().width/2);
});
function wrap(text, width) {
text.each(function () {
var text = d3.select(this),
words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1,
y = text.attr("y"),
dy = parseFloat(text.attr("dy")),
tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
}
}
});
}
.bar-chart {
background-color: #ccc;
}
.bar2 {
fill: steelblue;
}
.bar1 {
fill: #f2f2f2;
}
text {
font-size: 12px;
text-anchor: middle;
}
.bar-label text {
text-anchor: start;
}
path.domain {
stroke-width: 0;
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div class="container">
<div id="graph"></div>
</div>
小提琴链接: http://jsfiddle.net/xsuL8q4j/
希望这会有所帮助.
这篇关于d3中的钢筋位置与轴不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!