Question

I am trying to put words and their frequency on a bar chart using google charts. I have got all the data and I am passing it to the web page. On the webpage though I am getting the following error - Data column(s) for axis #0 cannot be of type string

Here is the code to get that data -

f = open('data/convertcsv.json')
data = json.loads(f.read())
f.close()
wordDict = {}
for row in data:
    # print row['sentiment']
    wordList = row['text'].split()
    for word in wordList:
         if len(word) < 4: continue
         if word in wordDict: wordDict[word] += 1
         else: wordDict[word] = 1
sorted_list = sorted(wordDict.iteritems(), key=operator.itemgetter(1))
final_list = sorted_list[-5:]
json_list = [['Word', 'Count']]
for item in final_list:
    json_list.append(list(item))
variables = {"politician_fname": politician_fname, "politician_lname": politician_lname, "popular_words": json.dumps(json_list)}
self.render_response('index.html', variables)

And here is the index.html-

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<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', {packages: ['corechart']});
    </script>
    <script type="text/javascript">
      function drawVisualization() {
        // Create and populate the data table.
        var data = google.visualization.arrayToDataTable([{{popular_words|safe}}]);

        // Create and draw the visualization.
        new google.visualization.BarChart(document.getElementById('visualization')).
            draw(data,
                 {title:"Maximum frequency words",
                  width:600, height:400,
                  vAxis: {title: "Words"},
                  hAxis: {title: "Count"}}
            );
      }


      google.setOnLoadCallback(drawVisualization);
    </script>
  </head>
  <body style="font-family: Arial;border: 0 none;">
    <div id="visualization" style="width: 600px; height: 400px;"></div>
  </body>
</html>

However when I copy paste the data I am getting in the GAE console on the index.html I can see the bar graph. Here is the data that I am getting on the console -

[["Word", "Count"], ["included", 225], ["politician", 236], ["Vote", 258], ["Varanasi", 272], ["Narendra", 280], ["TIME", 290], ["Indian", 398], ["#AAP", 409], ["Rahul", 430], ["Modi", 441]]
Was it helpful?

Solution

I suspect that the problem is that you have an extra layer of array in the data you pass to the arrayToDataTable method. Remove the [ and ] around {{popular_words|safe}}:

var data = google.visualization.arrayToDataTable({{popular_words|safe}});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top