2016-11-17 128 views
1

大家好,我從D3.JS開始,我想展示一個帶有溫度的酒吧。用D3創建條形圖

這是我的代碼

json_url= "https://data.cityofchicago.org/resource/7edu-s3u7.json"; 
var all_name_station = ["63rd Street Weather Station", "Foster Weather Station", "Oak Street Weather Station"]; 
var one_name_station = ["63rd Street Weather Station"]; 

var width = 900; 
var height = 400; 

$(document).ready(function(){ 
    d3.json(json_url, function(data) { 
    var canvas = d3.select("body") 
     .append("svg") 
     .attr("width", width) 
     .attr("height", height); 


    one_name_station.forEach(function(station_item){ 
       data.forEach(function(item_data){ 
      if (item_data["station_name"] == station_item){ 
       //console.log(item_data); 
      canvas.selectAll("rect") 
        .data(item_data) 
       .enter() 
        .append("rect") 
        .attr("width", function(d) {return d.air_temperature;}) 
        .attr("height", 50) 
        .attr("y", function(d,i){return d;}) 
        .attr("fill", "blue"); 
      } 
     }); 
    }); 
    }); 
}); 

我把我的數據從JSON,還有很多站,但我只啓動represente的數據"63rd Street Weather Station"

但我的問題是,這個代碼不返回沒有。你可以試試here

我想念的是什麼!

在此先感謝

回答

0

立即解決問題是,現在你是不是傳遞一個迭代到data,只是一個對象。如果你在一個數組包裹item_data它會創建一個單一的藍色矩形:

.data([item_data]) 

然後,你將有其他的問題,但是,如設置y。我建議將數據首先重新格式化爲對象列表(而不是一次追加一個對象),然後構建one of the canonical bar chart examples

+0

感謝@mdml,但爲什麼只顯示一個其他的吧,會發生什麼! – Stone

+0

@Stone:你需要改變你如何計算y。我不確定你的意圖,所以也許你可以澄清你的問題? – mdml

0

我會傳遞數組的數組,而不是一個項目。因此,編譯正確站第一的數組,然後把它傳遞給D3:

//array of objects 
var stations = [{name: "Station 1", air_temperature: 19.5}, 
          {name: "Station 2", air_temperature: 21.5}, 
          {name: "Station 3", air_temperature: 20},]; 
//adding bars 
var bars = canvas.selectAll("rect") 
       .data(stations) 
       .enter() 
        .append("rect") 
        .attr("width", function(d) {return d}) //guess: pass through function figuring out the right scale 
        .attr("height", 50) //guess: pass through function figuring out the right scale 
        .attr("y", function(d,i){return d.air_temperature;}) //guess: multiply by scaleFactor, obtained depending on number of entries in data and canvas size 
        .attr("fill", "blue"); //guess: pass through d3.scale.linear() function 
+0

Thanks @Vadim我對D3很新,我的JSON就像你的電臺陣列'https:// data.cityofchicago.org/resource/7edu-s3u7.json',但是如果我只想顯示station1和station3,會發生什麼事情 – Stone

+0

我也是)。在將數組放入如下的d3'data'中之前對其進行優化:var proper_list = function(all_stations,array_of_required_stations)\t返回all_stations.filter(s = – Vadim