D3:如何对多系列折线图使用exit()。remove() [英] D3: How to use exit().remove() for Multi-Series Line Chart

查看:108
本文介绍了D3:如何对多系列折线图使用exit()。remove()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于d3的多系列折线图( d3.v4.js ):

For the Multi-Series Line Chart of d3 (d3.v4.js):

https://bl.ocks.org/mbostock/3884955

如果我想用不同的输入数据重绘图表,那么 exit()。remove()的功能如何应用?

how has the exit().remove() functionality to be applied, if I want to redraw the chart with different input data?

function myGraphic(myData) {
    var svg = d3.select("svg"),
        margin = {top: 20, right: 80, bottom: 30, left: 50},
        width = svg.attr("width") - margin.left - margin.right,
        height = svg.attr("height") - margin.top - margin.bottom,
        g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");


    var x = d3.scaleTime().range([0, width]),
        y = d3.scaleLinear().range([height, 0]),
        z = d3.scaleOrdinal(d3.schemeCategory10);

    var line = d3.line()
        .x(function (d) {
            return x(d.date);
        })
        .y(function (d) {
            return y(d.temperature);
        });

    //noinspection JSUnresolvedVariable
    var data = myData.dataList;

    //noinspection JSUnresolvedVariable
    data.columns = ["date", "value1", myData.referenceName];

    var cities = data.columns.slice(1).map(function (id) {
        return {
            id: id,
            values: data.map(function (d) {
                return {date: d.date, temperature: d[id]};
            })
        };
    });


    x.domain(d3.extent(data, function (d) {
        return d.date;
    }));

    y.domain([
        d3.min(cities, function (c) {
            return d3.min(c.values, function (d) {
                return d.temperature;
            });
        }),
        d3.max(cities, function (c) {
            return d3.max(c.values, function (d) {
                return d.temperature;
            });
        })
    ]);

    z.domain(cities.map(function (c) {
        return c.id;
    }));

    var xAxisScale2 = d3.scaleTime()
        .domain([new Date(2014, 0, 1), new Date(2016, 0, 1, 0)])
        .rangeRound([20, width - 20]);

    var xAxis = d3.axisBottom(x);


    g.append("g")
        .attr("class", "axis axis--x")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis.ticks(d3.timeYear));

    g.append("g")
        .attr("class", "axis axis--y")
        .call(d3.axisLeft(y))
        .append("text")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", "0.71em")
        .attr("fill", "#000")
        .text("Temperature");


    var city = g.selectAll(".city")
        .data(cities)
        .enter().append("g")
        .attr("class", "city");


    city.append("path")
        .attr("class", "line")
        .attr("d", function (d) {
            return line(d.values);
        })
        .style("stroke", function (d) {
            return z(d.id);
        });

    city.append("text")
        .datum(function (d) {
            return {id: d.id, value: d.values[d.values.length - 1]};
        })
        .attr("transform", function (d) {
            return "translate(" + x(d.value.date) + "," + y(d.value.temperature) + ")";
        })
        .attr("x", 3)
        .attr("dy", "0.35em")
        .style("font", "10px sans-serif")
        .text(function (d) {
            return d.id;
        });

    city.exit().remove();

}

更新:

UPDATE:

我试图合并 @Gerardo Furtado 但是这里看起来仍然有问题:

I tried to incorporate the proposal of @Gerardo Furtado but something seems still to be wrong here:

<!DOCTYPE html>
<meta charset="utf-8">
<style>

    .axis--x path {
        display: none;
    }

    .line {
        fill: none;
        stroke: steelblue;
        stroke-width: 1.5px;
    }

</style>
<button>Click me</button>
<svg width="960" height="500"></svg>
<!--<script src="//d3js.org/d3.v4.min.js"></script>-->
<script src="d3.v4.js"></script>

<!--<script src="v03-exit-funktioniert-3-evolution.js"></script>-->

<script>

    var svg = d3.select("svg"),
        margin = {top: 20, right: 80, bottom: 30, left: 50},
        width = svg.attr("width") - margin.left - margin.right,
        height = svg.attr("height") - margin.top - margin.bottom,
        g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    var parseTime = d3.timeParse("%Y%m%d");

    var x = d3.scaleTime().range([0, width]),
        y = d3.scaleLinear().range([height, 0]),
        z = d3.scaleOrdinal(d3.schemeCategory10);

    var line = d3.line()
        .curve(d3.curveBasis)
        .x(function (d) {
            return x(d.date);
        })
        .y(function (d) {
            return y(d.temperature);
        });

    var data = [
        {"date": "1136156400000", "New York": 63.4, "San Francisco": 62.7, "Austin": 72.2},
        {"date": "1167692400000", "New York": 58.0, "San Francisco": 59.9, "Austin": 67.7},
        {"date": "1199228400000", "New York": 53.3, "San Francisco": 59.1, "Austin": 69.4},
        {"date": "1230850800000", "New York": 55.7, "San Francisco": 58.8, "Austin": 68.0},
        {"date": "1262386800000", "New York": 62.3, "San Francisco": 55.1, "Austin": 71.9}];

    var data2 = [
        {"date": "1136156400000", "New York": 163.4, "San Francisco": 262.7, "Austin": 372.2},
        {"date": "1167692400000", "New York": 158.0, "San Francisco": 259.9, "Austin": 367.7},
        {"date": "1199228400000", "New York": 153.3, "San Francisco": 259.1, "Austin": 369.4},
        {"date": "1230850800000", "New York": 155.7, "San Francisco": 258.8, "Austin": 368.0},
        {"date": "1262386800000", "New York": 162.3, "San Francisco": 255.1, "Austin": 371.9}];


    // d3.tsv("data.tsv", type, function (error, data) {
    //     if (error) throw error;

    data.columns = ["date", "New York", "San Francisco", "Austin"];

    var cities = data.columns.slice(1).map(function (id) {
        return {
            id: id,
            values: data.map(function (d) {
                return {date: d.date, temperature: d[id]};
            })
        };
    });

    x.domain(d3.extent(data, function (d) {
        return d.date;
    }));

    y.domain([
        d3.min(cities, function (c) {
            return d3.min(c.values, function (d) {
                return d.temperature;
            });
        }),
        d3.max(cities, function (c) {
            return d3.max(c.values, function (d) {
                return d.temperature;
            });
        })
    ]);
    g.append("g")
        .attr("class", "axis axis--x")
        .attr("transform", "translate(0," + height + ")")
        .call(d3.axisBottom(x));
    g.append("g")
        .attr("class", "axis axis--y")
        .call(d3.axisLeft(y))
        .append("text")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", "0.71em")
        .attr("fill", "#000")
        .text("Temperature, ºF");
    update();
    d3.select("button").on("click", function () {
        // cities.splice(0, 1);
        data = data2;
        console.log(cities);
//            console.log(JSON.stringify(cities));
        update();
    });

    function update() {
        data.columns = ["date", "New York", "San Francisco", "Austin"];
        cities = data.columns.slice(1).map(function (id) {
            return {
                id: id,
                values: data.map(function (d) {
                    return {date: d.date, temperature: d[id]};
                })
            };
        });


        x.domain(d3.extent(data, function (d) {
            return d.date;
        }));
        y.domain([
            d3.min(cities, function (c) {
                return d3.min(c.values, function (d) {
                    return d.temperature;
                });
            }),
            d3.max(cities, function (c) {
                return d3.max(c.values, function (d) {
                    return d.temperature;
                });
            })
        ]);
        z.domain(cities.map(function (c) {
            return c.id;
        }));
        var city = g.selectAll(".city")
            .data(cities);
        city.exit().remove();
        var cityEnter = city.enter().append("g")
            .attr("class", "city");
        cityEnter.append("path")
            .attr("class", "line")
            .attr("d", function (d) {
                return line(d.values);
            })
            .style("stroke", function (d) {
                return z(d.id);
            });
        cityEnter.append("text")
            .datum(function (d) {
                return {id: d.id, value: d.values[d.values.length - 1]};
            })
            .attr("transform", function (d) {
                return "translate(" + x(d.value.date) + "," + y(d.value.temperature) + ")";
            })
            .attr("x", 3)
            .attr("dy", "0.35em")
            .style("font", "10px sans-serif")
            .text(function (d) {
                return d.id;
            });
    }
    // });

    function type(d, _, columns) {
        d.date = parseTime(d.date);
        for (var i = 1, n = columns.length, c; i < n; ++i) d[c = columns[i]] = +d[c];
        return d;
    }


</script> 

UPDATE2:

UPDATE2:

(希望)只有一个关于标签名称及其位置的主题:

There is (hopefully) just one topic open regarding label names and their position:

<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
    .axis--x path {
        display: none;
    }

    .line {
        fill: none;
        stroke: steelblue;
        stroke-width: 1.5px;
    }

</style>
<button>Click me</button>
<svg width="960" height="500"></svg>
<!--<script src="//d3js.org/d3.v4.min.js"></script>-->
<script src="d3.v4.js"></script>

<!--<script src="v03-exit-funktioniert-3-evolution.js"></script>-->

<script>
    var svg = d3.select("svg"),
        margin = {
            top: 20,
            right: 80,
            bottom: 30,
            left: 50
        },
        width = svg.attr("width") - margin.left - margin.right,
        height = svg.attr("height") - margin.top - margin.bottom,
        g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    var parseTime = d3.timeParse("%Y%m%d");

    var x = d3.scaleTime().range([0, width]),
        y = d3.scaleLinear().range([height, 0]),
        z = d3.scaleOrdinal(d3.schemeCategory10);

    var line = d3.line()
        .curve(d3.curveBasis)
        .x(function (d) {
            return x(d.date);
        })
        .y(function (d) {
            return y(d.temperature);
        });

    var data = [{
        "date": "1136156400000",
        "Old York": 63.4,
        "San Francisco": 62.7,
        "Austin": 72.2
    }, {
        "date": "1167692400000",
        "Old York": 58.0,
        "San Francisco": 59.9,
        "Austin": 67.7
    }, {
        "date": "1199228400000",
        "Old York": 53.3,
        "San Francisco": 59.1,
        "Austin": 69.4
    }, {
        "date": "1230850800000",
        "Old York": 55.7,
        "San Francisco": 58.8,
        "Austin": 68.0
    }, {
        "date": "1262386800000",
        "Old York": 62.3,
        "San Francisco": 55.1,
        "Austin": 71.9
    }];

    var data2 = [{
        "date": "1136156400000",
        "New York": 263.4,
        "San Francisco": 262.7,
        "Austin": 372.2
    }, {
        "date": "1167692400000",
        "New York": 458.0,
        "San Francisco": 259.9,
        "Austin": -367.7
    }, {
        "date": "1199228400000",
        "New York": 153.3,
        "San Francisco": 259.1,
        "Austin": 369.4
    }, {
        "date": "1230850800000",
        "New York": 155.7,
        "San Francisco": 258.8,
        "Austin": 368.0
    }, {
        "date": "1262386800000",
        "New York": 162.3,
        "San Francisco": 255.1,
        "Austin": 371.9
    }];


    // d3.tsv("data.tsv", type, function (error, data) {
    //     if (error) throw error;

    data.columns = ["date", "Old York", "San Francisco", "Austin"];

    var cities = data.columns.slice(1).map(function (id) {
        return {
            id: id,
            values: data.map(function (d) {
                return {
                    date: d.date,
                    temperature: d[id]
                };
            })
        };
    });

    x.domain(d3.extent(data, function (d) {
        return d.date;
    }));

    y.domain([
        d3.min(cities, function (c) {
            return d3.min(c.values, function (d) {
                return d.temperature;
            });
        }),
        d3.max(cities, function (c) {
            return d3.max(c.values, function (d) {
                return d.temperature;
            });
        })
    ]);
    g.append("g")
        .attr("class", "axis axis--x")
        .attr("transform", "translate(0," + height + ")")
        .call(d3.axisBottom(x));
    g.append("g")
        .attr("class", "axis axis--y")
        .call(d3.axisLeft(y))
        .append("text")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", "0.71em")
        .attr("fill", "#000")
        .text("Temperature, ºF");
    update();
    d3.select("button").on("click", function () {
        // cities.splice(0, 1);
        data = data2;
        data.columns = ["date", "New York", "San Francisco", "Austin"];
        //            console.log(JSON.stringify(cities));
        update();
    });

    function update() {
        cities = data.columns.slice(1).map(function (id) {
            return {
                id: id,
                values: data.map(function (d) {
                    return {
                        date: d.date,
                        temperature: d[id]
                    };
                })
            };
        });


        x.domain(d3.extent(data, function (d) {
            return d.date;
        }));
        y.domain([
            d3.min(cities, function (c) {
                return d3.min(c.values, function (d) {
                    return d.temperature;
                });
            }),
            d3.max(cities, function (c) {
                return d3.max(c.values, function (d) {
                    return d.temperature;
                });
            })
        ]);
        z.domain(cities.map(function (c) {
            return c.id;
        }));
        var city = g.selectAll(".city")
            .data(cities);

        city.exit().remove();

        var cityEnter = city.enter().append("g")
            .attr("class", "city");

        cityEnter.append("path")
            .attr("class", "line")
            .attr("d", function (d) {
                return line(d.values);
            })
            .style("stroke", function (d) {
                return z(d.id);
            });

        cityEnter.append("text")
            .datum(function (d) {
                return {
                    id: d.id,
                    value: d.values[d.values.length - 1]
                };
            })
            .attr("transform", function (d) {
                return "translate(" + x(d.value.date) + "," + y(d.value.temperature) + ")";
            })
            .attr("x", 3)
            .attr("dy", "0.35em")
            .style("font", "10px sans-serif")
            .text(function (d) {
                return d.id;
            });

        city = cityEnter.merge(city);

        city.select("path").attr("d", function (d) {
            return line(d.values);
        });

        svg.select(".axis--y").call(d3.axisLeft(y))
    }
    // });

    function type(d, _, columns) {
        d.date = parseTime(d.date);
        for (var i = 1, n = columns.length, c; i < n; ++i) d[c = columns[i]] = +d[c];
        return d;
    }

</script>

UPDATE3:
试试对于标签(纽约与纽约) - 还没有工作......

UPDATE3: Try for the label (Old York vs. New York) - not working yet...

<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
    .axis--x path {
        display: none;
    }

    .line {
        fill: none;
        stroke: steelblue;
        stroke-width: 1.5px;
    }

</style>
<button>Click me</button>
<svg width="960" height="500"></svg>
<!--<script src="d3.v4.js"></script>-->

<script>
    var svg = d3.select("svg"),
        margin = {
            top: 20,
            right: 80,
            bottom: 30,
            left: 50
        },
        width = svg.attr("width") - margin.left - margin.right,
        height = svg.attr("height") - margin.top - margin.bottom,
        g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    var parseTime = d3.timeParse("%Y%m%d");

    var x = d3.scaleTime().range([0, width]),
        y = d3.scaleLinear().range([height, 0]),
        z = d3.scaleOrdinal(d3.schemeCategory10);

    var line = d3.line()
        .curve(d3.curveBasis)
        .x(function (d) {
            return x(d.date);
        })
        .y(function (d) {
            return y(d.temperature);
        });

    var data = [{
        "date": "1136156400000",
        "Old York": 63.4,
        "San Francisco": 62.7,
        "Austin": 72.2
    }, {
        "date": "1167692400000",
        "Old York": 58.0,
        "San Francisco": 59.9,
        "Austin": 67.7
    }, {
        "date": "1199228400000",
        "Old York": 53.3,
        "San Francisco": 59.1,
        "Austin": 69.4
    }, {
        "date": "1230850800000",
        "Old York": 55.7,
        "San Francisco": 58.8,
        "Austin": 68.0
    }, {
        "date": "1262386800000",
        "Old York": 62.3,
        "San Francisco": 55.1,
        "Austin": 71.9
    }];

    var data2 = [{
        "date": "1136156400000",
        "New York": 263.4,
        "San Francisco": 262.7,
        "Austin": 372.2
    }, {
        "date": "1167692400000",
        "New York": 458.0,
        "San Francisco": 259.9,
        "Austin": -367.7
    }, {
        "date": "1199228400000",
        "New York": 153.3,
        "San Francisco": 259.1,
        "Austin": 369.4
    }, {
        "date": "1230850800000",
        "New York": 155.7,
        "San Francisco": 258.8,
        "Austin": 368.0
    }, {
        "date": "1262386800000",
        "New York": 162.3,
        "San Francisco": 255.1,
        "Austin": 371.9
    }];


    // d3.tsv("data.tsv", type, function (error, data) {
    //     if (error) throw error;

    data.columns = ["date", "Old York", "San Francisco", "Austin"];

    var cities = data.columns.slice(1).map(function (id) {
        return {
            id: id,
            values: data.map(function (d) {
                return {
                    date: d.date,
                    temperature: d[id]
                };
            })
        };
    });

    x.domain(d3.extent(data, function (d) {
        return d.date;
    }));

    y.domain([
        d3.min(cities, function (c) {
            return d3.min(c.values, function (d) {
                return d.temperature;
            });
        }),
        d3.max(cities, function (c) {
            return d3.max(c.values, function (d) {
                return d.temperature;
            });
        })
    ]);
    g.append("g")
        .attr("class", "axis axis--x")
        .attr("transform", "translate(0," + height + ")")
        .call(d3.axisBottom(x));
    g.append("g")
        .attr("class", "axis axis--y")
        .call(d3.axisLeft(y))
        .append("text")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", "0.71em")
        .attr("fill", "#000")
        .text("Temperature, ºF");

    update();
    d3.select("button").on("click", function () {
        // cities.splice(0, 1);
        data = data2;
        data.columns = ["date", "New York", "San Francisco", "Austin"];
        //            console.log(JSON.stringify(cities));
        update();
    });

    function update() {
//        data.columns = ["date", "New York", "San Francisco", "Austin"];
        cities = data.columns.slice(1).map(function (id) {
            return {
                id: id,
                values: data.map(function (d) {
                    return {
                        date: d.date,
                        temperature: d[id]
                    };
                })
            };
        });


        x.domain(d3.extent(data, function (d) {
            return d.date;
        }));
        y.domain([
            d3.min(cities, function (c) {
                return d3.min(c.values, function (d) {
                    return d.temperature;
                });
            }),
            d3.max(cities, function (c) {
                return d3.max(c.values, function (d) {
                    return d.temperature;
                });
            })
        ]);
        z.domain(cities.map(function (c) {
            return c.id;
        }));

        var city = g.selectAll(".city")
            .data(cities);

        city.append("text")
            .datum(function (d) {
                return {
                    id: d.id,
                    value: d.values[d.values.length - 1]
                };
            })
            .attr("transform", function (d) {
                return "translate(" + x(d.value.date) + "," + y(d.value.temperature) + ")";
            })
            .attr("x", 3)
            .attr("dy", "0.35em")
            .style("font", "10px sans-serif")
            .text(function (d) {
                return d.id;
            });

        // var text = g.selectAll(".text")
        //     .data(texts);

        city.exit().remove();

        var cityEnter = city.enter().append("g")
            .attr("class", "city");

        cityEnter.append("path")
            .attr("class", "line")
            .attr("d", function (d) {
                return line(d.values);
            })
            .style("stroke", function (d) {
                return z(d.id);
            });


        city = cityEnter.merge(city);

        cityEnter.append("text")
        //        city.append("text")
            .datum(function (d) {
                return {
                    id: d.id,
                    value: d.values[d.values.length - 1]
                };
            })
            .attr("transform", function (d) {
                return "translate(" + x(d.value.date) + "," + y(d.value.temperature) + ")";
            })
            .attr("x", 3)
            .attr("dy", "0.35em")
            .style("font", "10px sans-serif")
            .text(function (d) {
                return d.id;
            });


        city.select("path")
        //            .transition().duration(1000)
            .attr("d", function (d) {
                return line(d.values);
            });

        city.select("text").datum(function (d) {
            return {
                id: d.id,
                value: d.values[d.values.length - 1]
            };
        })
        //            .transition().duration(1000)
            .attr("transform", function (d) {
                return "translate(" + x(d.value.date) + "," + y(d.value.temperature) + ")";
            });

        svg.select(".axis--y")
        //            .transition().duration(1000)
            .call(d3.axisLeft(y));
    }

</script>


推荐答案

现在你只是在Bostock的代码结束:

Right now you're just adding this line at the end of Bostock's code:

city.exit().remove();

然而,这不起作用,因为他的代码只有一个输入选择。

However, this will not work because his code has just one "enter" selection.

解决方案是创建数据绑定选择和分离的输入选择。这样,您将有一个工作退出选择:

The solution is creating a data-binding selection and a separated "enter" selection. That way, you'll have a working "exit" selection:

var city = g.selectAll(".city")
    .data(cities);

city.exit().remove();

var cityEnter = city.enter().append("g")
    .attr("class", "city");

cityEnter.append("path")
    //etc...

cityEnter.append("text")
    //etc..

每次单击顶部的按钮时,这是一个带有该更改的演示bl.ocks它删除了数据数组中的第一个对象,并且退出选择删除了该行:

Here is a demo bl.ocks with that change, every time you click the button at the top it removes the first object in the data array, and the exit selection removes the line:

https://bl.ocks.org/anonymous/98204ee0226e2f6178154b7903f9ef99

编辑:在您的原始问题中,您只询问退出选择。由于您实际上询问更新选择,这是一个新的演示,更新行,文本和轴:

EDIT: In your original question you only asked about the exit selection. Since you are actually asking about the update selection, here is a new demo, updating the lines, the texts and the axis:

<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
  .axis--x path {
    display: none;
  }
  
  .line {
    fill: none;
    stroke: steelblue;
    stroke-width: 1.5px;
  }

</style>
<button>Click me</button>
<svg width="960" height="500"></svg>
<!--<script src="//d3js.org/d3.v4.min.js"></script>-->
<script src="d3.v4.js"></script>

<!--<script src="v03-exit-funktioniert-3-evolution.js"></script>-->

<script>
  var svg = d3.select("svg"),
    margin = {
      top: 20,
      right: 80,
      bottom: 30,
      left: 50
    },
    width = svg.attr("width") - margin.left - margin.right,
    height = svg.attr("height") - margin.top - margin.bottom,
    g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  var parseTime = d3.timeParse("%Y%m%d");

  var x = d3.scaleTime().range([0, width]),
    y = d3.scaleLinear().range([height, 0]),
    z = d3.scaleOrdinal(d3.schemeCategory10);

  var line = d3.line()
    .curve(d3.curveBasis)
    .x(function(d) {
      return x(d.date);
    })
    .y(function(d) {
      return y(d.temperature);
    });

  var data = [{
    "date": "1136156400000",
    "New York": 63.4,
    "San Francisco": 62.7,
    "Austin": 72.2
  }, {
    "date": "1167692400000",
    "New York": 58.0,
    "San Francisco": 59.9,
    "Austin": 67.7
  }, {
    "date": "1199228400000",
    "New York": 53.3,
    "San Francisco": 59.1,
    "Austin": 69.4
  }, {
    "date": "1230850800000",
    "New York": 55.7,
    "San Francisco": 58.8,
    "Austin": 68.0
  }, {
    "date": "1262386800000",
    "New York": 62.3,
    "San Francisco": 55.1,
    "Austin": 71.9
  }];

  var data2 = [{
    "date": "1136156400000",
    "New York": 163.4,
    "San Francisco": 262.7,
    "Austin": 372.2
  }, {
    "date": "1167692400000",
    "New York": 158.0,
    "San Francisco": 259.9,
    "Austin": 367.7
  }, {
    "date": "1199228400000",
    "New York": 153.3,
    "San Francisco": 259.1,
    "Austin": 369.4
  }, {
    "date": "1230850800000",
    "New York": 155.7,
    "San Francisco": 258.8,
    "Austin": 368.0
  }, {
    "date": "1262386800000",
    "New York": 162.3,
    "San Francisco": 255.1,
    "Austin": 371.9
  }];


  // d3.tsv("data.tsv", type, function (error, data) {
  //     if (error) throw error;

  data.columns = ["date", "New York", "San Francisco", "Austin"];

  var cities = data.columns.slice(1).map(function(id) {
    return {
      id: id,
      values: data.map(function(d) {
        return {
          date: d.date,
          temperature: d[id]
        };
      })
    };
  });

  x.domain(d3.extent(data, function(d) {
    return d.date;
  }));

  y.domain([
    d3.min(cities, function(c) {
      return d3.min(c.values, function(d) {
        return d.temperature;
      });
    }),
    d3.max(cities, function(c) {
      return d3.max(c.values, function(d) {
        return d.temperature;
      });
    })
  ]);
  g.append("g")
    .attr("class", "axis axis--x")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x));
  g.append("g")
    .attr("class", "axis axis--y")
    .call(d3.axisLeft(y))
    .append("text")
    .attr("transform", "rotate(-90)")
    .attr("y", 6)
    .attr("dy", "0.71em")
    .attr("fill", "#000")
    .text("Temperature, ºF");
  update();
  d3.select("button").on("click", function() {
    // cities.splice(0, 1);
    data = data2;
    //            console.log(JSON.stringify(cities));
    update();
  });

  function update() {
    data.columns = ["date", "New York", "San Francisco", "Austin"];
    cities = data.columns.slice(1).map(function(id) {
      return {
        id: id,
        values: data.map(function(d) {
          return {
            date: d.date,
            temperature: d[id]
          };
        })
      };
    });


    x.domain(d3.extent(data, function(d) {
      return d.date;
    }));
    y.domain([
      d3.min(cities, function(c) {
        return d3.min(c.values, function(d) {
          return d.temperature;
        });
      }),
      d3.max(cities, function(c) {
        return d3.max(c.values, function(d) {
          return d.temperature;
        });
      })
    ]);
    z.domain(cities.map(function(c) {
      return c.id;
    }));
    var city = g.selectAll(".city")
      .data(cities);

    city.exit().remove();

    var cityEnter = city.enter().append("g")
      .attr("class", "city");

    cityEnter.append("path")
      .attr("class", "line")
      .attr("d", function(d) {
        return line(d.values);
      })
      .style("stroke", function(d) {
        return z(d.id);
      });

    cityEnter.append("text")
      .datum(function(d) {
        return {
          id: d.id,
          value: d.values[d.values.length - 1]
        };
      })
      .attr("transform", function(d) {
        return "translate(" + x(d.value.date) + "," + y(d.value.temperature) + ")";
      })
      .attr("x", 3)
      .attr("dy", "0.35em")
      .style("font", "10px sans-serif")
      .text(function(d) {
        return d.id;
      });

    city = cityEnter.merge(city);

    city.select("path").transition().duration(1000).attr("d", function(d) {
      return line(d.values);
    });

    city.select("text").datum(function(d) {
        return {
          id: d.id,
          value: d.values[d.values.length - 1]
        };
      }).transition().duration(1000)
      .attr("transform", function(d) {
        return "translate(" + x(d.value.date) + "," + y(d.value.temperature) + ")";
      })

    svg.select(".axis--y").transition().duration(1000).call(d3.axisLeft(y))
  }
  // });

  function type(d, _, columns) {
    d.date = parseTime(d.date);
    for (var i = 1, n = columns.length, c; i < n; ++i) d[c = columns[i]] = +d[c];
    return d;
  }

</script>

这篇关于D3:如何对多系列折线图使用exit()。remove()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆