大家好我从D3.JS开始,我想展示一个有温度的酒吧。
这是我的代码
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获取数据,有很多站,但我开始只代表"63rd Street Weather Station"
的数据
但我的问题是这段代码没有返回任何内容。您可以尝试here
我错过了什么!
提前致谢
答案 0 :(得分:0)
您当前的问题是,现在您没有将迭代传递给data
,只是一个对象。如果将item_data
包装在一个数组中,它将创建一个蓝色矩形:
.data([item_data])
然后,您将遇到其他问题,例如设置y
。我建议您首先将数据重新格式化为对象列表(而不是一次添加一个),然后构建one of the canonical bar chart examples。
答案 1 :(得分: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