我进行了广泛搜索,但无法弄清楚代码出了什么问题。抱歉,如果我缺少明显的内容。
我有一个JSON对象,如下所示:
var data={
"by_date":[
{"date":"2014-01-01", "count":10},
{"date":"2014-02-01", "count":20},
{"date":"2014-03-01", "count":30},
{"date":"2014-04-01", "count":15},
{"date":"2014-05-01", "count":20}
],
"by_location": {
"name":"World","children":[
{
"name":"United States", "children":[{"name":"New York", "children":[{"name":"Albany","count":5}, {"name":"NYC","count":5}]}]
},
{
"name":"Canda", "children":[
{
"name":"Alberta", "children":[{"name":"Edmonton","count":5},{"name":"Calgary","count":5}]
},
{
"name":"British Columbia", "children":[{"name":"Victoria","count":2},{"name":"Vancouver","count":8}]
}
]
},
{
"name":"China", "children":[{"name":"Beijing","count":30}]
},
{
"name":"India", "children":[{"name":"Bangalore","count":15}]
},
{
"name":"Germany", "children":[{"name":"Frankfurt","count":20}]
}
]
}
};
我想在同一HTML页面上使用来自
data.by_date
的数据和来自data.by_location
的可缩放Circlepack显示折线图。我有两个Javascript函数by_date
创建一个折线图,另一个by_location
创建一个Circlepack,它们都具有与Mike Bostock的折线图和zoomable circlepack示例完全相同的代码,我将它们称为:by_date(data.by_date);
by_location(data.by_location); // Creates circlepack, but zoom doesn't work.
问题在于,虽然折线图和Circlepack均已创建并显示在页面上,但缩放功能在circlepack上不起作用。我收到以下错误:
Uncaught TypeError: Cannot read property 'parent' of undefined
但是,如果我不打
by_date
而只打by_location
,它就可以正常工作。//by_date(data.by_date);
by_location(data.by_location); // Zoom works great now!
由于
by_date
仅使用data.by_date
,甚至不触摸data.by_location
,为什么要注释掉它使by_location
正常工作?以下是说明问题的小提琴:
线包和圆包(圆包都不会缩放):http://jsfiddle.net/xk5aqf8t/6/
折线图功能
by_date
已注释(缩放效果很好):http://jsfiddle.net/38sayeqa/请注意,两个小提琴之间的唯一区别是对
by_date
的注释调用。任何帮助是极大的赞赏。提前致谢!
最佳答案
您遇到的问题是,在缩放过渡中,您要选择文档中的所有text
元素,包括折线图,其中元素的绑定数据没有任何parent
属性(因此会出现错误消息)。
修复很容易。只需将转换选择约束到当前图表即可。在您的情况下,您已经选择了一些文本元素,您可以简单地重用它,如下所示:
// Let's keep our initial selection in the text variable:
var text = svg.selectAll('text').data(nodes);
text.enter()... // the entering selection is a subselection, so we keep it separate
// Create a new transition on the existing selection of text nodes
var transition = text.transition().duration(...); // the transition will reuse `text` selection
transition.filter(...); // don't subselect anything here
这是demo。