d3.js-来自同一JSON对象不同部分的同一页面上的多个图表

d3.js - multiple charts on same page from different parts of same JSON object

本文关键字:一页 同部 js- JSON 对象 d3      更新时间:2023-09-26

我搜索了很多遍,都没能找出我的代码出了什么问题。如果我遗漏了一些显而易见的东西,我深表歉意。

我有一个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的折线图和可缩放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/

请注意,这两个fiddle之间仅有区别是对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

这是一个演示