我是编程新手,我一直在研究O'Reilly Interactive Data Visualization书中的例子。D3 - 在美国地图上渲染多年的数据状态数据
现在,我正在努力将州电动汽车的5年数据可视化。每个州的颜色都会根据特定年份内注册的电动车辆的数量而变化。
问题:
每次我点击下拉菜单中year
,它会创建它下面另一个地图SVG。我怎样才能得到它重新呈现在同一(现有)地图SVG的数据?
背景:
我有一个定义了SVG的尺寸全局变量。我也有两个功能:
drawMap
有一年的论证,并建立了SVG,从CSV到us_map.json
加载数据,并创建所有的国界线。clickEventMap
将事件侦听器附加到每个年份按钮,然后调用drawMap
函数通过与按钮上年份匹配的年份。最后,我拨打drawMap(2013)
,以便页面默认为2013年的数据,然后致电clickEventMap()
。
我迄今为止尝试:
我console.log(year)
的D3 color.domain
方法和正确的一年之后被存储为在该点的一年变量。
另外,如果手动更改参数drawMap()
被调用时,我可以成功更改现有地图上呈现的数据。
我的代码:
var w = 1200;
var h = 800;
var barpadding = 1;
var drawMap = function(year) {
var svg = d3.select("body")
.append("svg")
.attr("height", h)
.attr("width", w);
var projection = d3.geo.albersUsa()
.translate([w/2, h/2])
.scale([1600]);
var path = d3.geo.path()
.projection(projection);
var color = d3.scale.quantize()
.range(["rgb(237, 248, 233)", "rgb(186, 228, 179)", "rgb(116,196,118)", "rgb(49, 163, 84)", "rgb(0, 109, 44)"]);
color.domain([
d3.min(data, function(d) {return d["electric_vehicles_" + year];}),
d3.max(data, function(d) { return d["electric_vehicles_" + year];})
]);
console.log(year);
d3.json("us-states.json", function(json) {
for (var i = 0; i < data.length; i ++) {
var dataState = data[i].state;
var dataValue = parseFloat(data[i]["electric_vehicles_" + year]);
for (var j = 0; j < json.features.length; j++) {
var jsonState = json.features[j].properties.name;
if (dataState === jsonState) {
json.features[j].properties.value = dataValue;
break;
}
}
}
var stateView = function() {
console.log("State clicked.");
location.href="/states/1";
svg.selectAll("path")
.data(json.features)
.enter()
.append("path")
.attr("d", path)
.style("fill", function(d) {
var value = d.properties.value;
if (value) {
return color(value);
}
else {
return "#ccc";
}
})
.on("mouseover", function(d, i) {
d3.select(this)
.style("fill-opacity", 0.5);
})
.on("mouseout", function(d, i) {
d3.selectAll("path")
.style("fill-opacity", 1);
})
.on("click", function() {
stateView();
});
});
});
};
var clickEventMap = function() {
$("#map2013").on("click", function() {
// var year = 2013;
drawMap(2013);
});
$("#map2012").on("click", function() {
// var year = 2012;
drawMap(2012);
});
$("#map2011").on("click", function() {
// var year = 2011;
drawMap(2011);
});
$("#map2010").on("click", function() {
// var year = 2010;
drawMap(2010);
});
$("#map2009").on("click", function() {
// var year = 2009;
drawMap(2009);
});
};
drawMap(2013);
clickEventMap();
感谢您的输入。
你能提供一个工作小提琴/ plnk/jsbin? – iulian