我正在尝试使用D3创建气泡图,但无法弄清楚为什么我的数据处理不正确。我已经从PHP导入了处理过的数据,现在我正在尝试运行bubble.node
,以便为图表的圆圈(半径,x坐标,y坐标等)应用相关的图形数据。相反,我目前收到错误:
Error: Invalid value for <g> attribute transform="translate(undefined,undefined)"
这是代码(到目前为止;由于错误而停在这里):
$(document).ready(function() {
// pull data from php file
var topFrequency = '<?php echo json_encode($frequencyJSON)?>';
var diameter = 510;
// create new pack layout
var bubble = d3.layout.pack()
.sort(null)
.size([diameter, diameter]);
// select chart3 div and append svg canvas for graph
var canvas = d3.select(".chart3").append("svg")
.attr("width", diameter)
.attr("height", diameter)
.append("g");
jsonData = JSON.parse(jsonData);
// should return array of nodes associated with data
// computed position of nodes & graphical data for each node
var nodes = bubble.nodes(topFrequency);
var node = canvas.selectAll(".node")
.data(nodes)
.enter()
.append("g")
// give nodes a class name for referencing
.attr("class", "node")
.attr("transform", function (d) {
return "translate(" + d.x + "," + d.y + ")";
});
});
topFrequency
在console.log
中显示如下:
{"name":"frequencyData",
"children":[
{
"author1":"TUYTTENS, FAM",
"frequency":7
},
{
"author1":"REVILLA, E",
"frequency":7
},
{
"author1":"ROPER, TJ",
"frequency":7
},
{
"author1":"MACDONALD, DW",
"frequency":6
},
{
"author1":"WOODROFFE, R",
"frequency":5
},
{
"author1":"CHEESEMAN, CL",
"frequency":4
},
{
"author1":"GALLAGHER, J",
"frequency":4
},
{
"author1":"KOWALCZYK, R",
"frequency":3
},
{
"author1":"HANCOX, M",
"frequency":3
},
{
"author1":"VIRGOS, E",
"frequency":3
}
]
}
据我所知,我上面遇到undefined
错误,因为x和y属性没有在节点数组中创建,但我无法弄清楚原因。也许我的数据格式不正确?
**编辑**
添加JSON.parse(topFrequency)
以获取格式正确的数据。现在console.log(jsonData)
给出了:
Object {name: "frequencyData", children: Array[10]}
children: Array[10]
0: Object
author1: "CARTES, JE"
depth: 1
frequency: 10
parent: Object
r: NaN
value: 0
x: NaN
y: NaN
1: Object
author1: "SASSEN, R"
depth: 1
frequency: 8
parent: Object
r: NaN
value: 0
x: NaN
y: NaN
2: Object
3: Object
4: Object
5: Object
6: Object
7: Object
8: Object
9: Object
length: 10
depth: 0
name: "frequencyData"
r: NaN
value: 0
x: NaN
y: NaN
虽然现在返回正确的属性,但它会为值返回NaN
。在我致电bubble.nodes
之前,它也是这样做的;我认为这些属性是由bubble.nodes
添加的!