[JAVA] Graph the power map of dogs and cats with Google Chart API and settle

In order to end the fight between dogs and cats, I made a page on the web to compare whether dogs or cats are attracting attention.

Comparison http://xiidec.appspot.com/vschart.html?q=dogs, cats

The result looks like this.

いぬねこひかく

Cat dominance. The number of Hatena bookmarks for the past 30 days is aggregated and graphed with the Google Chart API.

You can compare anything other than dogs and cats by entering keywords in the input box separated by commas.

PPR

KH

GEHA

All kinds of religious wars are over!

How it works

The mechanism is very simple.

  1. Get the Bukuma RSS for each keyword from Hatena Bookmark.
  2. Count the number of bookmarks.
  3. Generate a URL to call the Google Chart API and pass it to the client.

First first.

Hatena Bookmark provides new RSS for each keyword.

http://b.hatena.ne.jp/search/tag?q=cat & mode = rss

Just embed a keyword in this URL and access it. Then RSS will drop.

Next is the second.

Because it is difficult to measure popularity by the number of articles Count how many bookmarks you have. In XML

<hatena:bookmarkcount>16</hatena:bookmarkcount>

There is an item, so count it. By the way, this time I've only fetched articles within the last 30 days. If you want to see the date of the article

<dc:date>2005-12-22T14:40:18+09:00<<dc:date>

Just look at that.

Finally the third.

Introducing the Google Chart API. This is also easy to use.

https://chart.googleapis.com/chart?

After the URL

cht = [Graph type]

When

& chs = [Graph size]

When

& chd = [Graph parameters]

When

& chl = [label name]

With

https://chart.googleapis.com/chart?cht=p3&chs=400x200&chd=t:48,51&chl=%E7%8A%AC|%E7%8C%AB

Just create a URL like this.

Completed in no time. Here is the finished product.

vschart.py


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import webapp2
import os
import urllib
from google.appengine.ext.webapp import template
from datetime import datetime, timedelta
from xml.etree.ElementTree import *


class VsChart(webapp2.RequestHandler):
	def get(self):
		if self.request.get('q')!="":
			url=self.get_hatebu_chart_url(self.request.get('q').replace(" ",",").split(","))
		else:
			url=""
		q=self.request.get('q')
		template_values={
		'url':url,
		'q':q
		}
		path = os.path.join(os.path.dirname(__file__), 'html/vschart.html')
		self.response.out.write(template.render(path, template_values))
		
	def count_hatebu_tag(self,q):
		count=0
		ago_30=datetime.today()-timedelta(days=30)
		tree = parse(urllib.urlopen('http://b.hatena.ne.jp/search/tag?q=' + q + '&mode=rss'))
		for i in tree.findall('./{http://purl.org/rss/1.0/}item'):
			if ago_30 <= datetime.strptime(i.find('{http://purl.org/dc/elements/1.1/}date').text.split("T")[0], "%Y-%m-%d"):
				count += int(i.find('{http://www.hatena.ne.jp/info/xmlns#}bookmarkcount').text)
		return count
	
	def get_hatebu_chart_url(self,qList):
		countList=[]
		allCount=0
		for q in qList:
			count = self.count_hatebu_tag(q.encode("utf-8"))
			allCount+=count
			countList.append(count)
		if allCount != 0:
			perList = [str((c*100 / allCount)) for c in countList]
		else:
			perList = ["0"]*len(qList)
		return "https://chart.googleapis.com/chart?cht=p3&chs=400x200&chd=t:"+",".join(perList)+"&chl="+"|".join(qList)
			
			
app = webapp2.WSGIApplication([
	('/vschart.html', VsChart)
	], debug=True)

vschart.html


<html>
<head>
</head>
<body style="">
<p>&nbsp;</p>
<p>
<meta charset="UTF-8"></meta>
<title>Comparison-kun</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"></script>
<div data-role="page" id="first">
	<div data-role="content">	
		<h1>Which is more popular?</h1>
		<form action="/vschart.html" method="get">
Enter the comparison targets separated by commas. Let's compare the degree of attention on the net over the past month.
<input type="text" name="q" id="q" size="40" value="{{ q }}"><input type="submit" value="Compare">
		</form>
		<div>
			<img src="{{ url }}" alt="Dandelion">
		</div>
</div>
</div>
</body>
</html>

Summary

This time it was a pie chart, but there are various graphs such as bar graphs and line graphs. Check the Google reference page for more details!

Google Chart Tools:Image Charts (Deprecated) https://developers.google.com/chart/image/?hl=ja

Hmm ... Deprecated?

Important: The Image Charts portion of Google Chart Tools has been officially deprecated as of April 20, 2012. It will continue to work as per our deprecation policy.

Important: The image chart portion of Google's chart tool has been officially discontinued as of April 20, 2012. It will continue to work according to our deprecated policy.

Ehhhhhh The Google Chart API with images is no longer recommended It seems that you can use the new Google Chart API that uses Javascript and SVG.

I made it with much effort ...

Recommended Posts

Graph the power map of dogs and cats with Google Chart API and settle
See the power of speeding up with NumPy and SciPy
Get the trading price of virtual currency and create a chart with API of Zaif exchange
Introducing Google Map API with rails
Graph display of household power consumption with 3GPI and Raspberry Pi
Calculate the shortest route of a graph with Dijkstra's algorithm and Python
Read the graph image with OpenCV and get the coordinates of the final point of the graph
Get the number of articles accessed and likes with Qiita API + Python
[Rails 6 / Google Map API] Post an address and set multiple markers on the map
Get the stock price of a Japanese company with Python and make a graph
Display Google Maps API with Rails and pin display
Increase the font size of the graph with matplotlib
Compare the speed of Python append and map
Build API server for checking the operation of front implementation with python3 and Flask
Investigation of the relationship between speech preprocessing and transcription accuracy in the Google Cloud Speech API
Read the csv file with jupyter notebook and write the graph on top of it
Play with the power usage API provided by Yahoo
Visualize the range of interpolation and extrapolation with python
Book registration easily with Google Books API and Rails
Create a tweet heatmap with the Google Maps API
Get comments and subscribers with the YouTube Data API
Read the power of the smart meter with M5StickC (BP35C0-J11-T01)
Play music by hitting the unofficial API of Google Play Music
I tried to automatically post to ChatWork at the time of deployment with fabric and ChatWork Api
Try hitting the Twitter API quickly and easily with Python
About the camera change event of Google Maps Android API
[Django] Google map display of GIS data and graphing of parameters
Let's touch the API of Netatmo Weather Station with Python. #Python #Netatmo
Streamline information gathering with the Twitter API and Slack bots
Speech recognition of wav files with Google Cloud Speech API Beta
The story of creating a database using the Google Analytics API
Play with the password mechanism of GitHub Webhook and Python
[Map display] Display a map from the address registered by the user using the Google Maps JavaScript API and Geocoding API!
I tried hitting the Google API with Ruby and Python-Make the database a Spreadsheet and manage it with Google Drive