编辑:在西里尔正确解决问题后,我注意到只需将生成轴的函数放在用于生成标签的函数下面就可以解决问题。
我几乎读完了 O'Reilly 书中关于 D3.js 的教程,并在倒数第二页上制作了散点图,但是当添加以下代码来生成我的 X 轴时,超过一半的标签消失了:
// Define X Axis
var xAxis = d3.svg.axis()
.scale(xScale)
.orient('bottom');
// Generate our axis
svg.append('g')
.call(xAxis);
奇怪的是,在没有消失的标签中,留下的 3 个是我的数据集中最下面的 3 对([85,21]、[220,88]、[750,150]):
var myData = [
[5, 20],
...,
...,
[85, 21],
[220, 88],
[750,150]
];
这是正在发生的情况的图像,在顶部添加轴之前,每个点都有红色文本标签:
下面是生成散点图的其余代码,它几乎完全遵循书中解释的方法,我无法查明错误来自何处。
// =================
// = SCALED SCATTER GRAPH
// =================
var p = 30; // Padding
var w = 500 + p; // Width
var h = 500 + p; // Height
// SVG Canvas and point selector
var svg = d3.select('body')
.append('svg')
.attr('width',w)
.attr('height',h);
// Scales take an input value from the input domain and return
// a scaled value that corresponds to the output range
// X Scale
var xScale = d3.scale.linear()
.domain([0, d3.max(myData, function(d){
return d[0];
})])
.range([p, w - (p + p)]); // With padding. Doubled so labels aren't cut off
// Y Scale
var yScale = d3.scale.linear()
.domain([0, d3.max(myData, function(d){
return d[1];
})])
.range([h - p, p]); // With padding
// Radial scale
var rScale = d3.scale.linear()
.domain([0, d3.max(myData, function(d){ return d[1];})])
.range([2,5]);
// Define X Axis
var xAxis = d3.svg.axis()
.scale(xScale)
.orient('bottom');
// Generate our axis
svg.append('g')
.call(xAxis);
// Plot scaled points
svg.selectAll('circle')
.data(myData)
.đi vào()
.append('circle')
.attr('cx', function(d){
return xScale(d[0]);
})
.attr('cy', function(d){
return yScale(d[1]);
})
.attr('r', function(d){
return rScale(d[1]);
});
// Plot all labels
svg.selectAll('text')
.data(myData)
.đi vào()
.append('text')
.text(function(d){
trả lại d;
})
.attr('x', function(d){
return xScale(d[0]);
})
.attr('y', function(d){
return yScale(d[1]);
})
.style('fill', 'red')
.style('font-size',12);
js-fiddle:https://jsfiddle.net/z30cqeoo/
问题出在这里:
svg.selectAll('text')
x 轴和 y 轴使文本元素成为刻度,因此当轴存在时,上面的行将返回刻度数组,因此它解释了为什么添加轴时不显示.
所以正确的方法是这样做:
svg.selectAll('.text') //I am selecting those elements with class name text
svg.selectAll('.text')
.data(myData)
.đi vào()
.append('text')
.text(function(d){
console.log(d)
trả lại d;
})
.attr('x', function(d){
return xScale(d[0]);
})
.attr('y', function(d){
return yScale(d[1]);
})
.attr('class',"text") //adding the class
.style('fill', 'red')
.style('font-size',12);
完整工作代码đây .
Tôi là một lập trình viên xuất sắc, rất giỏi!