Google可视化表格图表 - 更改列名称

时间:2014-12-20 05:24:58

标签: javascript google-analytics google-visualization

如何更改Google表格图表中的列名?列名称显示为查询中给出的指标(ga:users | ga:sessions | ga:bounceRate)。我需要将它们显示为:users |会议| bounceRate。我是否必须创建新视图?或者做一些getcolumnLabel并改变它?

<head>
    <title>Google Charts</title>

    <script>

    (function(w,d,s,g,js,fs){
        g=w.gapi||(w.gapi={});g.analytics={q:[],ready:function(f){this.q.push(f);}};
        js=d.createElement(s);fs=d.getElementsByTagName(s)[0];
        js.src='https://apis.google.com/js/platform.js';
        fs.parentNode.insertBefore(js,fs);js.onload=function(){g.load('analytics');};
    }(window,document,'script'));
    </script>

    <script type="text/javascript" src="https://www.google.com/jsapi"></script>

    <script>

    gapi.analytics.ready(function() {
    var ACCESS_TOKEN = 'XXX'; // obtained from your service account

    gapi.analytics.auth.authorize({
        serverAuth: {
        access_token: ACCESS_TOKEN
        }
    });

    var data = new gapi.analytics.report.Data({
    query:  {
    ids: 'ga:XXX',
    metrics: 'ga:users,ga:sessions,ga:bounceRate',
    'start-date': '30daysAgo',
    'end-date': 'yesterday',
    output: 'dataTable'
        }
    });
    data.execute();

    data.on('success', function(response) {
    var data = new google.visualization.DataTable(response.dataTable);
    var formatter = new google.visualization.NumberFormat({fractionDigits: 0});
    formatter.format(data, 0);
    formatter.format(data, 1);
    var formatter = new google.visualization.NumberFormat({fractionDigits: 0, suffix: '%'});
    formatter.format(data, 2);
    var table = new google.visualization.Table(document.getElementById('test'));
    table.draw(data);
        });    
    });

    // Load the Visualization API and the chart package.
    google.load('visualization', '1', {'packages':['table']});
    });

    </script>

</head>

<body>             
                <div>
                    <div id="embed-api-auth-container"></div>
                    <div id="test"></div>     
                </div>    
</body>
</html>

1 个答案:

答案 0 :(得分:1)

列标题只是dataTable实例中的值,您已在success回调中使用了该值。

要重命名它们,只需执行以下操作:

response.dataTable.cols[0].label = 'Users';
response.dataTable.cols[1].label = 'Sessions';
response.dataTable.cols[2].label = 'Bounce Rate';

此外,您可能会或可能不会意识到您的代码中存在潜在的竞争条件。您正在加载Embed API,然后执行查询请求,并且您还要加载Google Visualization库,如下所示:

google.load('visualization', '1', {'packages':['table']});

虽然Embed API不太可能在加载gviz库之前加载并运行查询,但这肯定是可能的,如果发生这种情况你就会收到错误。