用不同的图表类型替换NVD3图表

Replace NVD3 chart with different chart type

本文关键字:类型 替换 NVD3 图表      更新时间:2023-12-06

我正在尝试用pieChart(NVD3型号)替换离散BarChart。是否有方法清理/更新图表或元素内容?

Html代码:

<div id="chart">
    <svg></svg>

图表初始化:

    nv.addGraph(function() {
    var xKey = 'label';
    var yKey = 'value';
    var chart = nv.models.discreteBarChart().x(function(d) {
        return d[xKey]
    }).y(function(d) {
        return d[yKey]
    }).staggerLabels(true)
    .tooltips(false).showValues(true).transitionDuration(250);
    d3.select('#chart svg').datum(defaultData()).call(chart);
    nv.utils.windowResize(chart.update);
    return chart;
});

以及我对替换现有图表的陈述:

function updateToPie(key1, key2) {
    var width = 500,
    height = 500;
    chart = nv.models.pieChart().x(function(d) {
        return d[key1]
    }).y(function(d) {
        return d[key2]
    }).color(d3.scale.category10().range()).width(width).height(height);
    d3.select("#chart svg").datum(chartData[0].values).transition()
            .duration(1200).attr('width', width).attr('height', height)
            .call(chart);
    chart.dispatch.on('stateChange', function(e) {
        nv.log('New State:', JSON.stringify(e));
    });
    return chart;
}

然而,这只是将piechart与现有的barchart重叠。任何帮助都是值得的。感谢

您可以通过运行来删除所有存在的内容

d3.selectAll("#chart svg > *").remove();

在添加新图表之前。