轴#0的数据列不能是google图表仪表板中的字符串类型

Data column(s) for axis #0 cannot be of type string in google chart dashboard

本文关键字:仪表板 字符串 类型 数据 不能 google      更新时间:2023-09-26

我正在尝试制作一个谷歌图表仪表板,并尝试了以下代码:

<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>
      Google Visualization API Sample
    </title>
    <script type="text/javascript" src="//www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load('visualization', '1.1', {packages: ['controls']});
    </script>

    <script type="text/javascript">
      function drawVisualization() {
          var listOfValues = document.getElementById("id1").value ;
          var temp2 = null;
          var temp3 = null ;
          var longArray = ['Year','Positive','Negative','Neutral','Comments','Status','Score'];
          var shortArrays = [], m, len;
          var arrayOfArray = [];
            var temp = listOfValues.split("-");
            for(var i=0; i<temp.length; i++){
                 temp2 = temp[i].split(',');
                if(temp2.length == 7){
                    for(var j=0; j<temp2.length;j++){
                     temp3 = temp2[j].split(',');
                     longArray.push(temp3[0]);
                }
                }
            }
            for (m = 0, len = longArray.length; m < len; m += 7) {
                shortArrays.push(longArray.slice(m, m + 7));
                console.log(shortArrays);
            }
            for (m = 0, len = shortArrays.length; m < len; m++) {
               arrayOfArray.push(shortArrays[m]);
            }

        // Prepare the data
         var data = google.visualization.arrayToDataTable(arrayOfArray); 

        // Define a category picker control for the Gender column
        var categoryPicker = new google.visualization.ControlWrapper({
          'controlType': 'CategoryFilter',
          'containerId': 'control2',
          'options': {
            'filterColumnLabel': 'Year',
            'ui': {
            'labelStacking': 'vertical',
              'allowTyping': false,
              'allowMultiple': true
            }
          }
        });
        // Define a category picker control for the Gender column
        var categoryPicker2 = new google.visualization.ControlWrapper({
          'controlType': 'CategoryFilter',
          'containerId': 'categoryPick2',
          'options': {
            'filterColumnLabel': 'Status',
            'ui': {
            'labelStacking': 'vertical',
              'allowTyping': false,
              'allowMultiple': true
            }
          }
        });

        //Define a combo chart
        var combo = new google.visualization.ChartWrapper({
            'chartType':'ComboChart',
            'containerId':'chart2',
              'options': {
                      'title' : 'Sentiment Analysis',
                      // setting the "isStacked" option to true fixes the spacing problem
                      'isStacked': false,
                      'height': 300,
                      'width': 300,
                      'vAxis': {title: "Sentiment"},
                      'hAxis': {title: "Month"},
                      'seriesType': "bars",
                      'series': {5: {type: "line"}}
                    },
                   // 'view': {'columns': [0, 1,2,3]}
                     'view': {
                        // set the columns to use in the chart's view
                        // calculated columns put data belonging to each country in the proper column
                        columns: [0,1,2,3] 
                     }

        });

        // Define a table
        var table = new google.visualization.ChartWrapper({
          'chartType': 'Table',
          'containerId': 'chart4',
          'options': {
              'view': {'columns': [1,2]},
            'width': '700px',
            'height':'100px'
          }
        });
        // Define a table
        var table2 = new google.visualization.ChartWrapper({
          'chartType': 'Table',
          'containerId': 'table2',
          'options': {
            'width': '200px'
          },
          'view': {'columns': [0,5]}
        });
      //Define a line chart
        var line = new google.visualization.ChartWrapper({
            'chartType':'LineChart',
            'containerId':'lineChart',
              'options': {
                 'label':'Sentiment Analysis'
                    },
                    'view': {'columns': [4,6]}
        });
        // Create a dashboard
       //   new google.visualization.Dashboard(document.getElementById('dashboard'));
        new google.visualization.Dashboard(document.getElementById('dashboard')).
            // Establish bindings, declaring the both the slider and the category
            // picker will drive both charts.
              bind([categoryPicker2], [line,table2]).
            bind([categoryPicker], [combo,table]).

            // Draw the entire dashboard.
            draw(data);
       //draw(data2);
   google.setOnLoadCallback(drawVisualization);

    </script>
  </head>

  <body style="font-family: Arial;border: 0 none;">
    <div id="dashboard">
      <table>
        <tr style='vertical-align: top'>
          <td style='width: 300px; font-size: 0.9em;'>
            <div id="control1"></div>
            <div id="control2"></div>
            <div id="control3"></div>
            <div id="categoryPick2"></div>
          </td>
          <td style='width: 600px'>
            <div style="float: left;" id="chart1"></div>
            <div style="float: left;" id="chart2"></div>
            <div style="float: right;" id="chart3"></div>
            <div style="float: right;" id="chart4"></div>
             <div style="float: right;" id="lineChart"></div>
              <div style="float: right;" id="table2"></div>
                     </td>
        </tr>
      </table>
      <input type="hidden"  id="id1" value=" ${listVal}" />
         <input type="hidden"  id="id2" value=" ${header1}" />
    </div>
   <div id="chart_div2" ></div>
  </body>
</html>

执行这段代码后,我得到表数据清楚;但是,它没有正确显示图表(我使用组合图和折线图)。它抛出以下错误:

"Data column(s) for axis #0 cannot be of type string"

谁能告诉我怎么解决这个问题?

谢谢。

当你提醒listOfValues时,你会得到这些值:

2010年、84年、65年,45岁的facebook,坏,12345 - 2011年,64年,75年,85年,facebook,坏,2345 -

基本上这些是数据库中的两行,我用连字符分隔。

为了绘制图表,您的数据系列必须是"number"类型(您的x轴数据可以是"string"类型)。由于要将字符串拆分为数组,因此数组元素都将是字符串。假设所有数据都是数字,可以替换这一行:

longArray.push(temp3[0]);
与这个:

longArray.push(parseFloat(temp3[0]));

或者this,如果你的数据都是整数:

longArray.push(parseInt(temp3[0], 10));

[编辑:处理不同数据类型的更完整答案]

有两种方法可以解决这个问题。第一种方法是预先定义列数据类型:

var longArray = [
    {label: 'Year', type: 'number'},
    {label: 'Positive', type: 'number'},
    {label: 'Negative', type: 'number'},
    {label: 'Neutral', type: 'number'},
    {label: 'Comments', type: 'string'},
    {label: 'Status', type: 'string'},
    {label: 'Score', type: 'number'}
];

您还可以在输入数据时进行一些粗略的类型检测:

for(var i=0; i<temp.length; i++){
    temp2 = temp[i].split(',');
    if(temp2.length == 7){
        for(var j=0; j<temp2.length;j++){
            // this does nothing except make temp2[j] into a 1-element array
            // temp3[0] === temp2[j], since you split on ',' already
            temp3 = temp2[j].split(',');
            if (temp3[0] == parseInt(temp3[0])) {
                longArray.push(parseInt(temp3[0]));
            }
            else if (temp3[0] == parseFloat(temp3[0])) {
                longArray.push(parseFloat(temp3[0]));
            }
            else {
                longArray.push(temp3[0]);
            }
        }
    }
}

你可以把这两种方法结合起来,以防出错。看他们在这里工作:http://jsfiddle.net/asgallant/xLKcx/

作为题外话,我建议清理您的代码—在构建数据数组的部分中有很多意大利面条式的代码。下面是一个简单的版本:http://jsfiddle.net/asgallant/xLKcx/1/