过渡不工作d3

Transition not working d3

本文关键字:d3 工作      更新时间:2023-09-26

我试图在d3中复制Gapminder(http://www.gapminder.org/tools/#_chart-type=bubbles)。当我使用过渡时,气泡不会像预期的那样移动。

我错过了什么吗?我如何将每年的所有气泡转换?

<!DOCTYPE html>
<html>
<head><title></title>
    <script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<script>
w = 1000;
h = 1000;
padding = 100;
dataset = [];
countries_uniq = [];
life_exp = [];
income_per_capita = [];
population = [];    
year_uniq = [];
xscale = d3.scaleLog().domain([2,500000]).range([170,w - padding]);
yscale = d3.scaleLinear().domain([0,85]).range([h - padding, padding]);
radScale = d3.scaleSqrt().domain([0,1e7]).range([0,10]);
xAxis = d3.axisBottom(xscale).ticks(8);
yAxis = d3.axisLeft(yscale);
svg = d3.select("body")
            .append("svg")
            .attr("width",w)
            .attr("height",h)
svg.append("g")
    .attr("transform", "translate(-90," + (h - padding - 90) + ")")
    .call(xAxis);
svg.append("g") 
    .attr("transform", "translate(" + 80 + ",-90)")
    .call(yAxis);
d3.csv("Gapminder_All_Time.csv",function(nations)
{
    console.log("inside function csv");
    var countries = [];
    var year = []
    dataset = nations;
    for(i=0;i<nations.length;i++) {
        countries.push(nations[i]["Country"]);
        year.push(nations[i]["Year"]);
    }
countries_uniq = Array.from(new Set(countries));
year_uniq = Array.from(new Set(year.sort()));
console.log(year_uniq)

function getDataByYear(year){
    var country_map = new Array();
    var found;
    for(k = 0; k < dataset.length; k++){
        if (parseInt(dataset[k]["Year"]) == year){
            found = true;
            cnt = dataset[k]["Country"];
            country_map.push({
                "LifeExp": (parseFloat(parseFloat((dataset[k]           
                ["LifeExp"])).toFixed(2))),
                "Income": (parseFloat((dataset[k]["GDP"]*1e6/dataset[k]         
                  ["Population"]).toFixed(2))),
                "Population": (parseInt(dataset[k]["Population"]))
            })
        }
    }
    return country_map;
}
var circle = svg.selectAll("circle")
                .data(getDataByYear(1900))
                .enter()
                .append("circle")
                .call(makeCircle)
function makeCircle(circle){
    circle.attr("cx",function(d) { return xscale(d.Income);})
    .attr("cy",function(d) { return yscale(d.LifeExp); })
    .attr("r", function(d) { return radScale(d.Population); })
}
svg.selectAll("circle")
    .transition()
    .duration(30000);
for(i=0;i<year_uniq.length;i++){
    var year = getDataByYear(year_uniq[i]);
    circle.data(year)
            .call(makeCircle)
    }
});
</script>
</body>
</html>

您需要在transition之后添加一些内容以实现实际的转换:

svg.selectAll("circle")
    .transition()
    .duration(30000)
    .???

参见https://bost.ocks.org/mike/transition/和https://github.com/d3/d3/wiki/API-Reference(搜索transition)