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

时间:2014-07-02 14:24:10

标签: javascript jquery google-visualization

我正在尝试制作一个Google图表信息中心并尝试使用以下代码:

<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,脸谱,坏,12345-2011,64,75,85,脸谱,坏,2345 -

基本上这些是数据库中的两行,我用连字符分隔。如果您需要更多详细信息,请与我们联系。

1 个答案:

答案 0 :(得分:5)

您的数据系列必须是&#34; number&#34;为了绘制图表(您的x轴数据可以是&#34;字符串&#34;)。由于您将字符串拆分为数组,因此数组元素都将是字符串。假设您的所有数据都是数字,则可以替换此行:

longArray.push(temp3[0]);

用这个:

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

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

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/