【问题标题】:Google Charts Rendering Empty Chart addRows() Errror谷歌图表渲染空图表添加行()错误
【发布时间】:2021-07-19 13:06:14
【问题描述】:

我有一个如下所示的 JavaScript 数组:

[
{x: "Station a", y: -77.33333333333333},
{x: "Station b", y: -19},
{x: "Station c", y: 9.492537313432836},
...
]

我希望使用 Google Charts 创建一个条形图。下面的代码给了我一个空图表......没有条形图。 x 值应该是标签,y 值在图表中创建条形。 我是否必须手动将数组值推送到数据表中?如果是这样,这将如何完成? 这是代码的摘录,n 是 JavaScript 数组:

// load necessary google charts libraries
google.charts.load("visualization", "1", {'packages':["corechart"]});
google.charts.load('current', {'packages':['bar']});

function plot1() {
        var dataPoints = []; // temporary array
        var n = []; // final array with data
        
        var chartData = new google.visualization.DataTable();
        chartData.addColumn('string', 'Station');
        chartData.addColumn('number', 'Arrival');
        
        n.forEach(function (row) {
            chartData.addRow([row.x, row.y]);
        });
        
        url = // localhost url with json data
        
        // push json data to array
        function addData(data) {
            for (var i = 0; i < data.length; i++) {
                for (var j = 0; j < data[i].delays.length; j++) {
                    dataPoints.push({
                        x: data[i].delays[j].Station,
                        y: data[i].delays[j].Arrival
                    });
                }
            }
            
            // filter "no information" values from array
            values = ["no information"]
            dataPoints = dataPoints.filter(item => !values.includes(item.y));
            
            // eliminate duplicates of x and get average of the y values
            const map = new Map();
            dataPoints.forEach(({ x, y }) => {
                const [total, count] = map.get(x) ?? [null, 0];
                map.set(x, [(total ?? 0) + parseInt(y), count + 1]);
            });
            
            // final array with data in desired format
            n = [...map].map(([k, v]) => ({ x: k, y: v[0] / v[1] }));
            
            console.log(n);
        }
        
        $.getJSON(url, addData);

        var options = {
            width: 700,
            legend: { position: 'none' },
            chart: {
            title: 'Verteilung der Verspätungen bei Ankunft (in Sekunden)'},
            axes: {
                x: {
                0: { side: 'top', label: 'Stationen'} // Top x-axis.
                }
            },
            bar: { groupWidth: "90%" }
                };
        
        var chart = new google.charts.Bar(document.getElementById('plot1'));
        chart.draw(chartData, google.charts.Bar.convertOptions(options));
    };

google.charts.setOnLoadCallback(plot1);

在我指定的 HTML 标头中

<script src = "http://code.jquery.com/jquery-latest.js"></script>
<script src = "https://www.gstatic.com/charts/loader.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

【问题讨论】:

    标签: javascript html charts google-visualization react-google-charts


    【解决方案1】:

    arrayToDataTable 需要一个简单的二维数组,只有内在值。
    以列标题作为第一行。

    var data = google.visualization.arrayToDataTable([
      ['Station', 'Arrival'],
      ['Station a', -77.33333333333333],
      ['Station b', -19],
    ]);
    

    您可以找到详细信息here

    它返回完整的数据表,所以后面不需要使用addColumn

    -- 或者--

    您可以创建一个空白数据表,然后添加列和行。

    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Station');
    data.addColumn('number', 'Arrival');
    
    n.forEach(function (row) {
      data.addRow([row.x, row.y]);
    });
    

    编辑

    $.getJSON 异步运行。所以你必须等到它完成,
    在数据可用之前。

    将循环移动到addData的末尾。
    然后在数据准备好后绘制图表。

    注意:您不需要第一个 load 语句。

    看下面的sn-p...

    google.charts.load('current', {
      packages: ['bar']
    }).then(plot1);
    
    function plot1() {
        var dataPoints = []; // temporary array
        var n = []; // final array with data
    
        var chartData = new google.visualization.DataTable();
        chartData.addColumn('string', 'Station');
        chartData.addColumn('number', 'Arrival');
    
        url = // localhost url with json data
    
        // push json data to array
        function addData(data) {
            for (var i = 0; i < data.length; i++) {
                for (var j = 0; j < data[i].delays.length; j++) {
                    dataPoints.push({
                        x: data[i].delays[j].Station,
                        y: data[i].delays[j].Arrival
                    });
                }
            }
    
            // filter "no information" values from array
            values = ["no information"]
            dataPoints = dataPoints.filter(item => !values.includes(item.y));
    
            // eliminate duplicates of x and get average of the y values
            const map = new Map();
            dataPoints.forEach(({ x, y }) => {
                const [total, count] = map.get(x) ?? [null, 0];
                map.set(x, [(total ?? 0) + parseInt(y), count + 1]);
            });
    
            // final array with data in desired format
            n = [...map].map(([k, v]) => ({ x: k, y: v[0] / v[1] }));
    
            console.log(n);
    
            n.forEach(function (row) {
                chartData.addRow([row.x, row.y]);
            });
    
    
            var options = {
                width: 700,
                legend: { position: 'none' },
                chart: {
                title: 'Verteilung der Verspätungen bei Ankunft (in Sekunden)'},
                axes: {
                    x: {
                    0: { side: 'top', label: 'Stationen'} // Top x-axis.
                    }
                },
                bar: { groupWidth: "90%" }
                    };
    
            var chart = new google.charts.Bar(document.getElementById('plot1'));
            chart.draw(chartData, google.charts.Bar.convertOptions(options));
    
        }
    
        $.getJSON(url, addData);
    
    };
    

    【讨论】:

    • 感谢您的帮助!我使用了你给出的循环示例,因为我必须动态添加数据......不幸的是,它抛出了一个错误,说明:未捕获(承诺中)错误:arrayToDataTable 的数据不是数组你可能需要其余代码来理解为什么这正在发生吗?我可以编辑我的帖子
    • 请注意上面的代码,在 OR 之后。没有arrayToDataTable -- 只有DataTable --> new google.visualization.DataTable();
    • arrayToDataTable是用于创建DataTable的静态方法,在第二个示例中,我们创建一个空白DataTable
    • 啊好的谢谢我改变了那部分...没有更多错误但仍然是一个空白图表:(
    • 干杯!乐意效劳。注意:您使用的是谷歌所谓的 Material 图表。 Material 图表不支持几个选项。见 --> Tracking Issue for Material Chart Feature Parity
    猜你喜欢
    • 2010-11-12
    • 1970-01-01
    • 1970-01-01
    • 2019-07-16
    • 2014-04-14
    • 2019-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多