2014-09-28 59 views
1

我搜遍了很多,我無法弄清楚我的代碼出了什麼問題。道歉,如果我失去了明顯的東西。d3.js - 來自同一個JSON對象的不同部分的同一頁上的多個圖表

我有一個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}] 
      } 
     ] 
    } 
}; 

我想顯示使用數據從data.by_datedata.by_location同一HTML頁面上可縮放circlepack折線圖和。我有兩個JavaScript函數by_date,它創建了一個折線圖,並by_location,它創建了一個circlepack,並且它們都具有完全相同的代碼爲邁克·博斯托克的路線圖和可縮放circlepack例子,我稱他們爲:

by_date(data.by_date); 
by_location(data.by_location); // Creates circlepack, but zoom doesn't work. 

問題是,雖然折線圖和圓形包都創建並顯示在頁面上,但縮放功能在圓形包上不起作用。我得到以下錯誤:

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工作好嗎?

這裏是小提琴演示該問題:

線路和circlepack(circlepack不放大):http://jsfiddle.net/xk5aqf8t/6/

線圖功能by_date評論(變焦正常工作):http://jsfiddle.net/38sayeqa/

注意只有這兩個小提琴之間的區別是by_date的評論呼叫。

任何幫助,非常感謝。提前致謝!

回答

1

你的情況的問題是,在你的縮放轉換中,你選擇文檔中的所有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

+0

謝謝奧列格!我完全錯過了transition.selectAll(「text」)選擇文檔中的所有文本節點的事實。非常感謝! – OrionMelt 2014-09-28 09:12:16