Tuesday, 24 January 2017

Geo Maps - with Usage of API key

Thursday, 28 May 2015

18. googleVis - The best of R and GoogleCharts

In a couple of earlier posts, we have seen how Google Charts can be used to generate online charts and graphs but the challenge was that were was a lot of rather messy javascript to play around with. All such mess has been rendered redundant with the R package googleVis and it is now possible to generate charts with the Google Charts API using only R.

The resultant charts need to be viewed in a browser -- and the html code is available for embedding in websites like this. This google docs spreadsheet has some data on milk production in Indian states. It has been downloaded and used for these exercises

Here is the code :


usePackage <- function(p) {
  if (!is.element(p, installed.packages()[,1]))
    install.packages(p, dep = TRUE)
  require(p, character.only = TRUE)
}

usePackage("googleVis")

StateMilk <- read.csv(file = "MilkState.tsv", head=TRUE, sep ='\t')
head(StateMilk)
StateMilkTotal <- StateMilk[, c("State","Total")]
StateName <- StateMilk[, "State"]
head(StateName)
head(StateMilkTotal)

GeoStates <- gvisGeoChart(StateMilk, "State", "Total", options=list(region="IN", displayMode="markers", resolution="provinces", width=1200, height=800))
plot(GeoStates)
GeoStates2 <- gvisGeoChart(StateMilk, "State", "Total", options=list(region="IN", displayMode="regions", resolution="provinces", width=600, height=400))
plot(GeoStates2)
print(GeoStates2)


and here is the chart that is generated by code printed out by the last print command
-----------------
Data: StateMilk • Chart ID: GeoChartIDe315e03b5c4 • googleVis-0.5.8
R version 3.0.2 (2013-09-25) • Google Terms of Use • Documentation and Data Policy
-----------------

In addition to maps, you can also draw bar and column charts like with this code

MilkBar <- gvisBarChart(StateMilk, xvar="State", yvar=c("CowMilkTotal", "BuffaloMilk"),options = list(width=800, height=900))
plot(MilkBar)

MilkColumn <- gvisColumnChart(StateMilk, xvar="State", yvar=c("CowMilkTotal", "BuffaloMilk"), options = list(width=800, height=900) )
plot(MilkColumn)


A complete list of sample code for all possible types of googleVis charts is available at on this page. All the examples can be executed by running the demo program as explained at the top of the reference page.

Sunday, 3 May 2015

17 Plotting Addresses on Google Maps using R and R GoogleMaps

In an earlier post, we had shown how locations as defined by addresses could be plotted on Google Maps but the process was rather complicated. First, the geocoding had to be done separately and secondly a lot of messy Javascript had to be coded by hand. Finally the map that was produced could only be viewed with an internet connection.

All these problems can now be overcome by using Rgooglemap package that is available from the R CRAN repository and so the process has become very simple. Finally, the map is generated like any R plot and can be saved as a PNG or PDF file for offline viewing.

Please see the code here :
#
# R program to show specific addresses on a Google Map
#

# the correct version was not available on CRAN
install.packages("/home/hduser/Downloads/rjson_0.2.13.tar.gz",repos=NULL, type="source")


setwd("/home/xxxx/xxx/maps")
library(rjson)
library(ggmap)
library(RgoogleMaps)
library(png)

#
# input data scraped off the web by running the python program
# https://github.com/prithwis/WebScraper/blob/master/SchoolDataScraper0.py
# the actual tsv file used in this exercise can be downloaded at
# https://github.com/prithwis/WebScraper/blob/master/CalcuttaSchools.tsv
#

Schools = read.csv(file="CalcuttaSchools.tsv",head=FALSE, sep="\t")

# since there is a limit on the number of geocoding requests that can be made, we work with only 5 schools
Schools = Schools[sample(1:nrow(Schools), 5, replace=FALSE),]
colnames(Schools) = c("Name", "Address")

# Lat, Lon is extracted along with address as understood by Google
GeoLocations = geocode(as.character(Schools$Address),output ='latlona')
MapData = cbind(Schools,GeoLocations)
names(MapData)[5] = "GooglePlace"
MapData = MapData[c("Name","lon","lat","Address","GooglePlace")]

# sanity check whether Address is similar to GooglePlace. If different, possible geolocation error
print(MapData[c("Address","GooglePlace","Name")])

# --------------------------------------------------------------------------

# Map is defined in terms of centre and zoom level
cent2 = c(mean(MapData$lat), mean(MapData$lon))
zoom2 = min(MaxZoom(range(MapData$lat), range(MapData$lon)))

# first get the map from Google as a png file
SchoolMap = GetMap(center = cent2, zoom = zoom2, destfile = "MapSchools.png", maptype = "map")
imgSchoolMap = readPNG("MapSchools.png")
grid::grid.raster(imgSchoolMap)

# Define set of long, lat to be plotted on map
LatSet = MapData$lat
LonSet = MapData$lon

# Plot points on the map
# to change plot symbols look at http://www.statmethods.net/advgraphs/parameters.html
PlotOnStaticMap(SchoolMap,lat = LatSet, lon = LonSet, cex = 0.7, pch = 6, col = "red", FUN = points, NEWMAP = TRUE)

# Name of the school, truncated to first 4 char, will be used as identify the points
NameSet = substr(as.character(MapData$Name),1,4)

# Location where name is printed, slightly different from the point plotted
LonOffSet2 = 0.005+LonSet

# Write names
PlotOnStaticMap(SchoolMap,lat = LatSet, lon = LonOffSet2, cex = 0.7, labels= NameSet, col = "black", FUN = text, add = T)

Couple of observations :

  1. The input to the program is a TSV file containing the names and addresses of 93 Schools in Calcutta. The TSV format is used because addresses typically contain "," and this can impact the reading process. The actual file used in this demo can be downloaded from github.
  2. This input file has been created with a Python program that has been used to "scrape" data from the a specific website. This Python program is also available in github.
  3. Google sets some limits on the number of geocoding requests that can be sent. So during the testing process, we take a random sample of 5 schools from the list of school addresses that we have downloaded.
  4. Finally, please note that the Google geocoding process is not totally reliable for addresses in India. Given the variety of address format, sometimes the Lat/Long retrieved is erroneous and the Calcutta schools can be placed in Iran or Mozambique! Or even in other locations in Calcutta, or West Bengal. Such things happen about 10% of the time. To spot and eliminate such obvious errors, we take a printout of the address supplied and the address generated by Google and compare the same. If they show significant differences it is best to remove this data or hand code the Lat / Long
  5. Finally putting text into a map is always tricky because text labels can overlap and cause a mess. In such cases it is far simpler to avoid text labels in R. Once the PNG file is generated, it is very easy to put in the text using any image editing software like Gimp or PhotoShop
Here are two maps generated by this program





Saturday, 2 May 2015

16. Using R for Maps of India - state, district, taluka level maps

Displaying spatial data on maps is always interesting but most Visualisation tools do not offer facilities to create maps of India, especially at the state and lower levels. In this post, we will show how such maps can be made.

The base data for such maps, the "polygons" that define the country, the states, the districts and even the talukas ( or sub-divisions) is available from an organisation called Global Administrative Areas or gadm.org. Country level files for almost all countries are available in a variety of formats including R and these are at three different levels. For India, these files can be downloaded as IND_admN.RData where N = 1,2,3. These will form the raw data from which we will create our maps.

Working with R, we will need two R packages :

# Load required libraries
library(sp)
library(RColorBrewer)

Assuming that the downloaded RData file is located in the R working directory, the following code will generate a basic India showing the states

# load level 1 india data downloaded from http://gadm.org/country
load("IND_adm1.RData")
ind1 = gadm

# simple map of India with states drawn
# unfortunately, Kashmir will get truncated
spplot(ind1, "NAME_1", scales=list(draw=T), colorkey=F, main="India")
Now suppose there is some data ( economic, demographic or whatever ...) and we wish to colour each state with a colour that represents this data. We simulate this scenario by assigning a random number ( between 0 and 1) to each state and then defining the RGB colour of this region with a very simple function that converts the data into a colour value. [ This idea borrowed from gis.stackexchange ]

# map of India with states coloured with an arbitrary fake data
ind1$NAME_1 = as.factor(ind1$NAME_1)
ind1$fake.data = runif(length(ind1$NAME_1))
spplot(ind1,"NAME_1",  col.regions=rgb(0,ind1$fake.data,0), colorkey=T, main="Indian States")

Now let us draw the map of any one state. First check the spelling of each state by listing the states:
ind1$NAME_1

and then executing these commands :
# map of West Bengal ( or any other state )
wb1 = (ind1[ind1$NAME_1=="West Bengal",])
spplot(wb1,"NAME_1", col.regions=rgb(0,0,1), main = "West Bengal, India",scales=list(draw=T), colorkey =F)

# map of Karnataka ( or any other state )
kt1 = (ind1[ind1$NAME_1=="Karnataka",])
spplot(kt1,"NAME_1", col.regions=rgb(0,1,0), main = "Karnataka, India",scales=list(draw=T), colorkey =F)


If we want to get and map district level data then we need to use the level 2 data as follows :

# load level 2 india data downloaded from http://gadm.org/country
load("IND_adm2.RData")
ind2 = gadm

and then plot the various districts as

# plotting districts of a State, in this case West Bengal
wb2 = (ind2[ind2$NAME_1=="West Bengal",])
spplot(wb2,"NAME_1", main = "West Bengal Districts", colorkey =F)


To identify each district with a beautiful colour we can use the following commands :
# colouring the districts with rainbow of colours
wb2$NAME_2 = as.factor(wb2$NAME_2)
col = rainbow(length(levels(wb2$NAME_2)))
spplot(wb2,"NAME_2",  col.regions=col, colorkey=T)

As in the case of the states, we can assume that each district has some (economic or demographic) data and we wish to colour the districts according to the intensity of this data, then we can use the following code :

# colouring the districts with some simulated, fake data
wb2$NAME_2 = as.factor(wb2$NAME_2)
wb2$fake.data = runif(length(wb2$NAME_1)) 
spplot(wb2,"NAME_2",  col.regions=rgb(0,wb2$fake.data, 0), colorkey=T)


But we can be even more clever by allocating certain shades of colour to certain ranges of data as with this code, adapted from this website

# colouring the districts with range of colours
col_no = as.factor(as.numeric(cut(wb2$fake.data, c(0,0.2,0.4,0.6,0.8,1))))
levels(col_no) = c("<20%", "20-40%", "40-60%","60-80%", ">80%")
wb2$col_no = col_no
myPalette = brewer.pal(5,"Greens")
spplot(wb2, "col_no", col=grey(.9), col.regions=myPalette, main="District Wise Data")


To move to the district, sub-division ( or taluk) level we need to use the level three data file :

# load level 3 india data downloaded from http://gadm.org/country
load("IND_adm3.RData")
ind3 = gadm

# extracting data for West Bengal
wb3 = (ind3[ind3$NAME_1=="West Bengal",])

and then plot the subdivision or taluk level map as follows :

#plotting districts and sub-divisions / taluk
wb3$NAME_3 = as.factor(wb3$NAME_3)
col = rainbow(length(levels(wb3$NAME_3)))
spplot(wb3,"NAME_3", main = "Taluk, District - West Bengal", colorkey=T,col.regions=col,scales=list(draw=T))


Now let us get a map of the district - North 24 Parganas. Make sure that the name is spelt correctly.

# get map for "North 24 Parganas District"
wb3 = (ind3[ind3$NAME_1=="West Bengal",])
n24pgns3 = (wb3[wb3$NAME_2=="North 24 Parganas",])
spplot(n24pgns3,"NAME_3", colorkey =F, scales=list(draw=T), main = "24 Pgns (N) West Bengal")

and within North 24 Parganas district, we can go down to the Basirhat Subdivision ( Taluk) and draw the map as follows: 

# now draw the map of Basirhat subdivision
# recreate North 24 Parganas data
n24pgns3 = (wb3[wb3$NAME_2=="North 24 Parganas",])
basirhat3 = (n24pgns3[n24pgns3$NAME_3=="Basirhat",])
spplot(basirhat3,"NAME_3", colorkey =F, scales=list(draw=T), main = "Basirhat,24 Pgns (N) West Bengal")


This is the highest resolution ( or lowest administrative division ) that we can go with data from gadm. However even within a map,  one "zoom" into and enlarge an area by specifying the latitude and longitudes of a zoom box as shown here.

# zoomed in data
wb2 = (ind2[ind2$NAME_1=="West Bengal",])
wb2$NAME_2 = as.factor(wb2$NAME_2)
col = rainbow(length(levels(wb2$NAME_2)))
spplot(wb2,"NAME_2",  col.regions=col,scales=list(draw=T),ylim=c(23.5,25),xlim=c(87,89), colorkey=T)



With this it should be possible to draw any map of India. For more comprehensive examples of such maps, please see this page.


Here is the entire code

========================================
setwd("/home/xxx/yyy/maps")

# http://r-nold.blogspot.in/2012/08/provincial-map-using-gadm.html
# http://blog.revolutionanalytics.com/2009/10/geographic-maps-in-r.html
# http://gis.stackexchange.com/questions/80565/plotting-a-map-of-new-zealand-with-regional-boundaries-in-r
# https://ryouready.wordpress.com/2009/11/16/infomaps-using-r-visualizing-german-unemployment-rates-by-color-on-a-map/
# http://rstudio-pubs-static.s3.amazonaws.com/6772_441847b522584d1095daddc2677e4ddb.html -- comprehensive 

# Load required libraries
library(sp)
library(RColorBrewer)

# load level 1 india data downloaded from http://gadm.org/country
load("IND_adm1.RData")
ind1 = gadm

# simple map of India with states drawn
# unfortunately, Kashmir will get truncated 
spplot(ind1, "NAME_1", scales=list(draw=T), colorkey=F, main="India")

# map of India with states coloured with an arbitrary fake data
ind1$NAME_1 = as.factor(ind1$NAME_1)
ind1$fake.data = runif(length(ind1$NAME_1))
spplot(ind1,"NAME_1",  col.regions=rgb(0,ind1$fake.data,0), colorkey=T, main="Indian States")


# list of states avaialable
ind1$NAME_1

# map of West Bengal ( or any other state )
wb1 = (ind1[ind1$NAME_1=="West Bengal",])
spplot(wb1,"NAME_1", col.regions=rgb(0,0,1), main = "West Bengal, India",scales=list(draw=T), colorkey =F)
# map of Karnataka ( or any other state )
kt1 = (ind1[ind1$NAME_1=="Karnataka",])
spplot(kt1,"NAME_1", col.regions=rgb(0,1,0), main = "Karnataka, India",scales=list(draw=T), colorkey =F)

# --------------------------------------------------------------------------------------
# load level 2 india data downloaded from http://gadm.org/country
load("IND_adm2.RData")
ind2 = gadm

# plotting districts of a State, in this case West Bengal
wb2 = (ind2[ind2$NAME_1=="West Bengal",])
spplot(wb2,"NAME_1", main = "West Bengal Districts", colorkey =F)

# colouring the districts with some simulated, fake data
wb2$NAME_2 = as.factor(wb2$NAME_2)
wb2$fake.data = runif(length(wb2$NAME_1)) 
spplot(wb2,"NAME_2",  col.regions=rgb(0,wb2$fake.data, 0), colorkey=T)

# colouring the districts with rainbow of colours
# wb2$NAME_2 = as.factor(wb2$NAME_2)
col = rainbow(length(levels(wb2$NAME_2)))
spplot(wb2,"NAME_2",  col.regions=col, colorkey=T)

# colouring the districts with range of colours
col_no = as.factor(as.numeric(cut(wb2$fake.data, c(0,0.2,0.4,0.6,0.8,1))))
levels(col_no) = c("<20%", "20-40%", "40-60%","60-80%", ">80%")
wb2$col_no = col_no
myPalette = brewer.pal(5,"Greens")
spplot(wb2, "col_no", col=grey(.9), col.regions=myPalette, main="District Wise Data")

# --------------------------------------------------------------------------------------
# load level 3 india data downloaded from http://gadm.org/country
load("IND_adm3.RData")
ind3 = gadm

# extracting data for West Bengal
wb3 = (ind3[ind3$NAME_1=="West Bengal",])

#plotting districts and sub-divisions / taluk
wb3$NAME_3 = as.factor(wb3$NAME_3)
col = rainbow(length(levels(wb3$NAME_3)))
spplot(wb3,"NAME_3", main = "Taluk, District - West Bengal", colorkey=T,col.regions=col,scales=list(draw=T))

# get list of districts avaialable
wb3$NAME_2

# get map for "North 24 Parganas District"
wb3 = (ind3[ind3$NAME_1=="West Bengal",])
n24pgns3 = (wb3[wb3$NAME_2=="North 24 Parganas",])
spplot(n24pgns3,"NAME_3", colorkey =F, scales=list(draw=T), main = "24 Pgns (N) West Bengal")

n24pgns3$NAME_3 = as.factor(n24pgns3$NAME_3)
n24pgns3$fake.data = runif(length(n24pgns3$NAME_3))
spplot(n24pgns3,"NAME_3", col.regions=rgb(0, n24pgns3$fake.data, 0), colorkey=T,scales=list(draw=T))

# get map for "South 24 Parganas District"
s24pgns3 = (wb3[wb3$NAME_2=="South 24 Parganas",])
spplot(s24pgns3,"NAME_3", colorkey =F, scales=list(draw=T), main = "24 Pgns (S) West Bengal")

s24pgns3$NAME_3 = as.factor(s24pgns3$NAME_3)
s24pgns3$fake.data = runif(length(s24pgns3$NAME_3))
spplot(s24pgns3,"NAME_3", col.regions=rgb(0, s24pgns3$fake.data, 0), colorkey=T,scales=list(draw=T),main = "24 Pgns (S) West Bengal")


# get map for "Murshidabad District"
mur3 = (wb3[wb3$NAME_2=="Murshidabad",])
spplot(mur3,"NAME_3", colorkey =F, scales=list(draw=T), main = "Murshidabad West Bengal")

mur3$NAME_3 = as.factor(mur3$NAME_3)
mur3$fake.data = runif(length(mur3$NAME_3))
spplot(mur3,"NAME_3", col.regions=rgb(0,0, mur3$fake.data), colorkey=T,scales=list(draw=T),main = "Murshidabad West Bengal")

# now draw the map of Basirhat subdivision
# recreate North 24 Parganas data
n24pgns3 = (wb3[wb3$NAME_2=="North 24 Parganas",])
basirhat3 = (n24pgns3[n24pgns3$NAME_3=="Basirhat",])
spplot(basirhat3,"NAME_3", colorkey =F, scales=list(draw=T), main = "Basirhat,24 Pgns (N) West Bengal")

# now draw the map of Baharampur subdivision
# recreate Murshidabad data
mur3 = (wb3[wb3$NAME_2=="Murshidabad",])
bahar3 = (mur3[mur3$NAME_3=="Baharampur",])
spplot(bahar3,"NAME_3", colorkey =F, scales=list(draw=T), main = "Baharampur, Murshidabad, West Bengal")

# -------------------------------------------------------------------------------------------
# load level 2 india data downloaded from http://gadm.org/country
load("IND_adm2.RData")
ind2 = gadm

# plotting selected districts of a State, in this case West Bengal
wb2 = (ind2[ind2$NAME_1=="West Bengal",])
spplot(wb2,"NAME_1", main = "West Bengal Districts", scales=list(draw=T),ylim=c(23.5,25),colorkey =F)

# zoomed in data
wb2 = (ind2[ind2$NAME_1=="West Bengal",])
wb2$NAME_2 = as.factor(wb2$NAME_2)
col = rainbow(length(levels(wb2$NAME_2)))
spplot(wb2,"NAME_2",  col.regions=col,scales=list(draw=T),ylim=c(23.5,25),xlim=c(87,89), colorkey=T)


PostScript

While we have achieved much, what was missing was the ability to mark cities on the map and write the names next to the points marked. To do so, we require 
  1. a function for geocoding place names into lon, lat values
  2. usage of the sp.layout option to place markers and texts on the map.
This has now been done, and you can see the three towns in West Bengal marked as follows


# Marking towns on the GADM maps
# On a map of West Bengal, we will now mark some towns
#
#load level 2 india data downloaded from http://gadm.org/country
# 

library(ggmap) # -- for geocoding, obtaining city locations
load("IND_adm2.RData")
ind2 = gadm

# plotting districts of a State, in this case West Bengal
wb2 = (ind2[ind2$NAME_1=="West Bengal",])

nam = c("Purulia","Bankura","Midnapur")
pos = geocode(nam)
tlat = pos$lat+0.05    # -- the city name will be above the marker
cities = data.frame(nam, pos$lon,pos$lat,tlat)
names(cities)[2] = "lon"
names(cities)[3] = "lat"


text1 = list("panel.text", cities$lon, cities$tlat, cities$nam,col="red", cex = 0.75)
mark1 = list("panel.points", cities$lon, cities$lat, col="blue")
text2 = list("panel.text",87.0,26.0,"GADM map", col = "dark green", cex = 1.2)
spplot(wb2, "NAME_1",
       sp.layout=list(text1,mark1, text2),
       main="West Bengal Districts",
       colorkey=FALSE, scales=list(draw=TRUE))



to change plot symbols look at http://www.statmethods.net/advgraphs/parameters.html

Wednesday, 23 April 2014

15. Motion Charts

Watch this video

Then make your own motion charts by either writing code, or better still simply using Google Docs.



was created with data on Tata Group stock prices from Quandl and residing on this Google Docs sheet

Monday, 3 March 2014

14. IBM Many Eyes

Many Eyes is another excellent tool that allows you to create very nice vizualizations that you can publish like this.
----
---

This visualisation was done by following this tutorial and using text of Vivekananda's at Chicago taken from this website. You can also explore other types of visualisations using the same data.

Wednesday, 19 February 2014

13. Google Fusion Tables - Tutorial

Google Fusion tables is an excellent free tool that allows you to create visualisations very easily. This map shows the locations of Airports in India. To understand how this was done, please follow this tutorial.

Here is another tutorial that shows how to turn spreadsheets into interactive maps, and here is a a workshop on Google Fusion Tables.

Thursday, 13 February 2014

12 Tableau - Getting Started

Tableau is an extremely powerful tool to create beautiful visualizations without having to bother about writing any kind of code.  It is a "pure" drag and drop tool that is ideal for all those who are allergic to programming. Unfortunately, Tableau is neither free, nor open source. But unlike SAS and other snooty products, Tableau very kindly offers us a free public version that you can download. To get started with Tableau, you can try out this tutorial and walk through to the end, you would be able to create beautiful charts that you host -- but only publicly -- at on your website, like this !


or this

Here are some more relevent resources
1. A set of data files that you can practice with.
2. A tutorial with good data from General Social Survey
3. A quick start guide with corresponding data from Super Store.
4. A white paper from Tableau on Which Chart is Right for You !
New Resources added in Jan 2016
5. Tekslate Tutorial on Tableau - including interview questions
6. Analytics Vidhya Introduction to Tableau
7. MuLin Tutorial -- quite nice

Tuesday, 31 December 2013

11 RIL stock data from Quandl - Filtered on a range of dates

This is an improvement on the chart shown in the previous post where NSE data was picked up in CSV format from Quandl - an excellent source of global timeseries data -- and shown in a candlestick format. Since the data that we are plotting this time, Reliance share prices, goes back a long time. We will be using a RangeFilter to choose the start and end dates of our plot. The big challenge in this case was to convert the date data obtained from Quandl which was in STRING format into the DATE format that is required by the  RangeFilter. This was done by using the code very kindly provide by ASGALLANT.The final chart is seen on this html page and also in this blog page.

Vizualyse PK



<head>
   <title>Vizualyse PK</title>
   <script src="https://www.google.com/jsapi"></script>
   <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
   <script src="http://prithwis.x10.bz/charts/jquery.csv-0.71.js"></script> 
<!--   <script src="https://jquery-csv.googlecode.com/files/jquery.csv-0.71.js"></script> -->
   <script type='text/javascript'>
   // load the visualization library from Google and set a listener
   google.load("visualization", "1", {packages:["corechart","controls"]});
   google.setOnLoadCallback(drawCandlefromQuandlPK);
//-------------------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------------
   function drawCandlefromQuandlPK(){
   
   var dashboardPK = new google.visualization.Dashboard(
       document.getElementById('div_dashboardPK'));
//----------------------------------------------------------------------------------------------------------------------------------------       
   var controlPK = new google.visualization.ControlWrapper({
     'controlType': 'ChartRangeFilter',
     'containerId': 'div_controlPK',
     'options': {
       // Filter by the date axis.
       'filterColumnIndex': 0,
       'ui': {
         'chartType': 'LineChart',
         'chartOptions': {
  //         'chartArea': {'width': '90%'},
           'hAxis': {'baselineColor': 'none'}
         },
         // Display a single series that shows the closing value of the stock.
         // Thus, this view has two columns: the date (axis) and the stock value (line series).
         'chartView': {
           'columns': [0, 4]
         },
         // 1 day in milliseconds = 24 * 60 * 60 * 1000 = 86,400,000
         'minRangeSize': 86400000
       }
     },
     // Initial range: 2007-11-31 to 2008-09-31.
     'state': {'range': {'start': new Date(2007, 10, 31), 'end': new Date(2008, 8, 31)}}
   });
 //--------------------------------------------------------------------------------------------------------------------------------------------
   var chartPK = new google.visualization.ChartWrapper({
     'chartType': 'CandlestickChart',
     'containerId': 'div_chartPK',
     'options': {
       title: "Reliance Stock Prices at NSE from Quandl",
       // Use the same chart area width as the control for axis alignment.
//       'chartArea': {'height': '80%', 'width': '90%'},
//       'hAxis': {'slantedText': false},
          'vAxis': {'viewWindow': {'min': 0, 'max': 3500}},
       'legend': {'position': 'none'}
     },
   });
//--------------------------------------------------------------------------------------------------------------------------------------------
     // grab the CSV
         //  $.get("https://www.quandl.com/api/v1/datasets/NSE/RELIANCE.csv?&trim_start=1998-03-20&trim_end=2013-12-27&collapse=weekly&
         $.get("https://www.quandl.com/api/v3/datasets/NSE/RELIANCE.csv??&auth_token=xxxxxxxxxxxxxxxxxxxxx&trim_start=1998-03-20&trim_end=2013-12-27&collapse=weekly&sort_order=desc", function(csvStringPK) {
         // transform the CSV string into a 2-dimensional array
            var arrayDataPK = $.csv.toArrays(csvStringPK, {onParseValue: $.csv.hooks.castToScalar});
         // this new DataTable object holds all the data
            var dataPK = new google.visualization.arrayToDataTable(arrayDataPK);
            
         // this view selects only a subset of the data, that is columns 0,3,1,5,2 that is appropriate for the candlestick chart
         // more importantly it converts the 0th column from string to date using the example given in http://jsfiddle.net/asgallant/8RFsB/1/
         // the string to date conversion is very important as otherwise the ControlWrapper will not work
            
            var viewPK = new google.visualization.DataView(dataPK);
            viewPK.setColumns([{
                type: 'date',
                label: dataPK.getColumnLabel(0),
                calc: function (dt, row) {
                    // split the string into date and time
                    var valArr = dt.getValue(row, 0).split(' ');
                    // split the date into year, month, day
                    var dateArr = valArr[0].split('-');
                   // create a new Date object from the data
                   // note that we subtract 1 from the month to convert to javascripts 0-index
                   var date = new Date(dateArr[0], dateArr[1] - 1, dateArr[2]);
                  // return the date and the formatted value as set in the original DataTable
                  return {
                      v: date,
                      f: dt.getFormattedValue(row, 0)
                  };
               }
          }, 3, 1,5,2]);
            
  //-----------------------------------------------------------------------------------------------------------------------------------------------          
    
        dashboardPK.bind(controlPK, chartPK);
        dashboardPK.draw(viewPK);
         });
   }
   </script>
</head>
<body>
<div id="div_dashboardPK">
<div id="div_chartPK" style="height: 600px; width: 900px;">
</div>
<div id="div_controlPK" style="height: 50px; width: 900px;">
</div>
</div>
</body>


an earlier post on dashboards also talks about filters in some detail. however the code is possibly cleaner here.

Sunday, 29 December 2013

10 Plotting NSE stock price data from Quandl

Quandl is a really fantastic source for all kinds of really useful financial data. For example you can see historical data on Tata Steel stock prices here. We will use this data to plot a Google Candlestick chart that shows open, close, high, low data for the Tata Steel stock both in a regular HTML page and in the blog below.

Google Chart Example


There are couple of interesting things in the following code that are interesting to know about.

  • While pulling the CSV data from Quandl, you can specify the start/end dates and the level of aggregation, that is daily, weekly, monthly
  • Google Candlestick charts expect the data to be in a certain order. Quandl provides the data in a different order and the columns needs to be rearranged. Hence the data table called "data" is converted into a view called "view" where we select columns 0,1,2,3,5 and reorder them into 0,3,1,5,2
  • This view and not the data is used to draw the chart



<head>
   <title>Google Chart Example</title>
   <script src="https://www.google.com/jsapi"></script>
   <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
   <script src="http://prithwis.x10.bz/charts/jquery.csv-0.71.js"></script> -->
<!--   <script src="https://jquery-csv.googlecode.com/files/jquery.csv-0.71.js"></script> -->
   <script type='text/javascript'>
   // load the visualization library from Google and set a listener
   google.load("visualization", "1", {packages:["corechart"]});
   google.setOnLoadCallback(drawCandlefromQuandl);
  
   function drawCandlefromQuandl(){
     // grab the CSV
         $.get("https://www.quandl.com/api/v3/datasets/NSE/TATASTEEL.csv?api_key=xxxxxx.xxxxx&collapse=weekly&start_date=2012-12-31&end_date=2014-12-31", function(csvString) {
         // transform the CSV string into a 2-dimensional array
            var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
         // this new DataTable object holds all the data
            var data = new google.visualization.arrayToDataTable(arrayData);
         // this view can select a subset of the data at a time
            var view = new google.visualization.DataView(data);
            view.setColumns([0,3,1,5,2]);
         var options = {
         title: "Tata Steel NSE Stock Prices from Quandl",
          hAxis: {title: view.getColumnLabel(0), minValue: view.getColumnRange(0).min, maxValue: view.getColumnRange(0).max},
          vAxis: {title: "Price in INR"},
          legend: 'none'
          };
          var chart = new google.visualization.CandlestickChart(document.getElementById('QuandlCandle'));
          chart.draw(view, options);
         });
   }
   </script>
</head>
<body>
   <div id="QuandlCandle" style="width: 900px; height: 500px;"> </div>   
</body>



Quandl provides a huge amount of data and this makes the chart rather clumsy. Our next step would be to see how to provide a control so that you can specify the dates of your data rather than hardcoding the same into the java script.

Monday, 23 December 2013

9 Interactive Dashboard with Google Charts with external CSV data

As an extension of the previous post where we used to data in CSV format available from an externally hosted source like Quandl to draw charts, we now see to inject a measure of interactivity into the same chart. The original CSV file containing data on education in India has lots of data columns. In this example, we will see how we can choose any one column of data and draw the corresponding chart either in an HTML page or in this blog. This example is based on the tutorial given in Economistry.


Google Chart Example


Please do note that in the URL pointing to the CSV file, we have added a sorting criteria as otherwise the graph is drawn in a reversed time scale, with newer data in the left and older data in the right.


<head>
   <title>Google Chart Example</title>
   <script src="https://www.google.com/jsapi"></script>
   <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
   <script src="http://prithwis.x10.bz/charts/jquery.csv-0.71.js"></script> 
<!--   <script src="https://jquery-csv.googlecode.com/files/jquery.csv-0.71.js"></script> -->
   <script type="text/javascript">
   // load the visualization library from Google and set a listener
   google.load("visualization", "1", {packages:["corechart"]});
   google.setOnLoadCallback(drawChartfromCSV);
  
   function drawChartfromCSV(){
     // grab the CSV
         $.get("https://www.quandl.com/api/v3/datasets/MOSPI/EDU_INST_SCHOOL_EXPENDTR_29_1.csv?api_key=xxxxxx...xxx&trim_start=2001-06-30&trim_end=2011-06-30&sort_order=asc", function(csvString) {
         // transform the CSV string into a 2-dimensional array
            var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
         // use arrayData to load the select elements with the appropriate options
              for (var i = 1; i < arrayData[0].length; i++) {       // i starts from 1, not 0 because the first column is text
            // this adds the given option to both select elements
              $("select").append("<option value='" + i + "'>" + arrayData[0][i] + "</option");
              }
              
         // set the default selection
            $("#range option[value='1']").attr("selected","selected");
         // this new DataTable object holds all the data
            var data = new google.visualization.arrayToDataTable(arrayData);
         // this view can select a subset of the data at a time
            var view = new google.visualization.DataView(data);
            view.setColumns([0,1]);
         var options = {
         title: "EDUCATIONAL INSTITUTIONS, SCHOOLS AND EXPENDITURE - INDIA",
          hAxis: {title: data.getColumnLabel(0), minValue: data.getColumnRange(0).min, maxValue: data.getColumnRange(0).max},
          vAxis: {title: data.getColumnLabel(1), minValue: data.getColumnRange(1).min, maxValue: data.getColumnRange(1).max},
          legend: 'none'
          };
          var chart = new google.visualization.LineChart(document.getElementById('csv2chart'));
          chart.draw(view, options);
          // this part makes the chart interactive
          
          $("select").change(function(){
          
          // determine selected  range - Vertical Axis
          
           var range = +$("#range option:selected").val();
          // update the view
             view.setColumns([0,range]);
          // update the options
          
             options.vAxis.title = data.getColumnLabel(range);
             options.vAxis.minValue = data.getColumnRange(range).min;
             options.vAxis.maxValue = data.getColumnRange(range).max;
             
          // update the chart
             chart.draw(view, options);
          });
         });
   }
   </script>
</head>
<body>
   <div id="csv2chart" style="height: 500px; width: 900px;">
 </div>
<select id="range">Choose your chart</select>
</body>



The original tutorial in Economistry allows one to choose both the domain (horizontal axis) and the range (vertical axis) but given the nature of the data, having anything other than year on the horizontal axis would make no sense.

8 Google Charts from Public CSV datasets

Quandl is a fantastic source of data collected from various agencies, curated with care and then made available either on their website or as CSV or JSON files that can be downloaded or used directly from your application. On registration you get access to your personal key that allows you to access the data more frequently than what is allowed in unregistered access. Registration is free.

In this example, we see how we can access CSV data about education in India from Quandl and publish it either on an HTML page or in blog. This example is based on the excellent tutorial available at Economistry except that the locations of source data and the JS libraries used have been changed so that one does not need to have a dedicated webserver to serve the files.

Google Chart Example


The Javascript library jquery.csv-0.71.js is required to convert CSV files into a format that is acceptable to the Google Data Table. You can download this from this URL, as explained in the Economistry tutorial and then upload it into your own webserver if you want to be assured of being able to access it whenever. Otherwise, if you are on a blog and cannot upload a file, you can link to it directly over the web as shown in the listing below.


<head>
   <title>Google Chart Example</title>
   <script src="https://www.google.com/jsapi"></script>
   <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
   <script src="http://prithwis.x10.bz/charts/jquery.csv-0.71.js"></script> 
<!--   <script src="https://jquery-csv.googlecode.com/files/jquery.csv-0.71.js"></script>-->
   <script type='text/javascript'>
   // load the visualization library from Google and set a listener
   google.load("visualization", "1", {packages:["corechart"]});
   google.setOnLoadCallback(drawChartfromCSV);
  
   function drawChartfromCSV(){
     // grab the CSV
         $.get("https://www.quandl.com/api/v3/datasets/MOSPI/EDU_INST_SCHOOL_EXPENDTR_29_1.csv?api_key=xxxxxxxxxxx..xxx", function(csvString) {
         // transform the CSV string into a 2-dimensional array
            var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
         // this new DataTable object holds all the data
            var data = new google.visualization.arrayToDataTable(arrayData);
         // this view can select a subset of the data at a time
            var view = new google.visualization.DataView(data);
            view.setColumns([0,2]);
         var options = {
         title: "EDUCATIONAL INSTITUTIONS, SCHOOLS AND EXPENDITURE - INDIA",
          hAxis: {title: data.getColumnLabel(0), minValue: data.getColumnRange(0).min, maxValue: data.getColumnRange(0).max},
          vAxis: {title: data.getColumnLabel(2), minValue: data.getColumnRange(2).min, maxValue: data.getColumnRange(2).max},
          legend: 'none'
          };
          var chart = new google.visualization.LineChart(document.getElementById('csv2chart'));
          chart.draw(view, options);
         });
   }
   </script>
</head>
<body>
   <div id="csv2chart" style="width: 900px; height: 500px;"> </div>   
</body>


In the next example, we will explore how to make these charts more interactive. Stay tuned.

Friday, 20 December 2013

7 Creating a Dashboard - Part II

Here we take the same data used in the previous post and convert it into a dashboard. We have replaced the chart with a chart wrapper. Added three filters. Added a dashboard component and bound the three filters to the chart wrapper. You can see the result both in this blog as well as on this regular HTML page.

The Dashboard on this blog

Data Source

sOne can choose one or multiple states. Also one can specify the range of cow and buffalo milk production and so select only the states that have this production.


<head>
    <script src="https://www.google.com/jsapi" type="text/javascript"></script>
    <script type="text/javascript">
     google.load('visualization', '1', {'packages': ['corechart','controls']});
     google.setOnLoadCallback(drawDashBoardMQ);
    
    function drawDashBoardMQ() {
            var queryMQ = new google.visualization.Query(
      'https://docs.google.com/a/yantrajaal.com/spreadsheet/ccc?key=0AhEX55Pfl1eedExUbS1xNzBuQVAyNDJTeG1weFQxbXc&sheet=MilkProduction&range=B2:H37&headers=1');
      queryMQ.setQuery('select B,E,F'); 
      queryMQ.send(handleQueryResponseMQ);
    };
    
    function handleQueryResponseMQ(responseMQ) {
      if (responseMQ.isError()) {
       alert('Error in query: ' + responseMQ.getMessage() + ' ' + responseMQ.getDetailedMessage());
       return;
     }
  
   var dashboardMQ = new google.visualization.Dashboard(document.getElementById('dash_divMQ')); 
 
 // Create a filter, passing some options
 // to filter out some rows based on value of column Cow Milk Total
   var CowMilkRangeSlider = new google.visualization.ControlWrapper({
    'controlType': 'NumberRangeFilter',
    'containerId': 'cowfilter_MQ',
    'options': {
      'filterColumnLabel': 'Cow Milk Total',
      'label' : 'Cow',
      'minValue': 0.0,
      'maxValue': 5000.0
    }
   });
  
  // Create a filter, passing some options
  // to filter out some rows based on value of column Buffalo Milk
   var BuffaloMilkRangeSlider = new google.visualization.ControlWrapper({
    'controlType': 'NumberRangeFilter',
    'containerId': 'buffalofilter_MQ',
    'options': {
      'filterColumnLabel': 'Buffalo Milk',
      'minValue': 0.0,
      'maxValue': 5000.0
    }
   });
  
   // Create a filter, passing some options
   // to filter out rows based on value of column State
   var StateFilter = new google.visualization.ControlWrapper({
    'controlType': 'CategoryFilter',
    'containerId': 'Statefilter_MQ',
    'options': {
      'filterColumnLabel': 'State',
      'ui': {
          'labelStacking': 'vertical',
          'allowTyping': false,
          'allowMultiple': true,
          'caption' : 'Choose State'
        },
     
    }
   });
  
  // Create a chart, passing some options
  // This is a chart wrapper
  var ColChartMQ = new google.visualization.ChartWrapper({
    'chartType': 'ColumnChart',
    'containerId': 'chart_divMQ',
    'options': {
      'width': 900,
      'height': 600,
      'title' : 'Milk Production',
      'hAxis': {title: 'State', titleTextStyle: {color: 'red'}},
    }
  }); 
  // Connect the three filters to the same chart
     dashboardMQ.bind([CowMilkRangeSlider,BuffaloMilkRangeSlider,StateFilter], ColChartMQ);
     
  // Get the data   
    var dataMQ = responseMQ.getDataTable();
    
  // Publish everything through teh dashboard
   dashboardMQ.draw(dataMQ)
   
}

    </script>
  </head>
  <body>
  <h3>
The Dashboard on this blog </h3>
<div id="dash_divMQ">
    <div id="Statefilter_MQ" style="height: 50px; width: 900px;">
</div>
<div id="chart_divMQ" style="height: 600px; width: 900px;">
</div>
<div id="cowfilter_MQ" style="height: 50px; width: 900px;">
</div>
<div id="buffalofilter_MQ" style="height: 50px; width: 900px;">
</div>
</div>
<a href="https://docs.google.com/a/yantrajaal.com/spreadsheet/ccc?key=0AhEX55Pfl1eedExUbS1xNzBuQVAyNDJTeG1weFQxbXc&amp;usp=drive_web#gid=1" target="_blank">Data Source</a>
  </body>



for some reason, the data from the first row, Andhra Pradesh, cannot be seen on the dashboard even though it is visible in previous normal Column Chart !!

A more sophisticated RangeFilter is shown in this post.

7 Creating a Dashboard - Part 1

When  you have a lot of data to be shown on a page, it makes sense to give the viewer an opportunity to filter some of the data so that he or she gets a cleaner view. In this case, we will first draw a rather clumsy Column Chart and then in the next section. The data for the chart is drawn from this spreadsheet. The chart shown below can also be seen in this regular HTML page.

Basic Column Chart Showing All Data

Data Source

Note how we have specified
  • the  Google Docs spreadsheet : https://docs.google.com/a/yantrajaal.com/spreadsheet/ccc?key=0AhEX55Pfl1eedExUbS1xNzBuQVAyNDJTeG1weFQxbXc
  • the sheet : sheet=MilkProduction
  • range : range=B2:H37
  • headers : headers=1
  • columns : query.setQuery('select B,E,F');
  • chart type : var chartMQ = new google.visualization.ColumnChart(document.getElementById('chart_divMQ'));


<head>
    <script src="https://www.google.com/jsapi" type="text/javascript"></script>
    <script type="text/javascript">
     google.load('visualization', '1', {'packages': ['corechart','controls']});
     google.setOnLoadCallback(drawColChartMQ);
    
    function drawColChartMQ() {
      var query = new google.visualization.Query(
      'https://docs.google.com/a/yantrajaal.com/spreadsheet/ccc?key=0AhEX55Pfl1eedExUbS1xNzBuQVAyNDJTeG1weFQxbXc&sheet=MilkProduction&range=B2:H37&headers=1');
      query.setQuery('select B,E,F'); 
      query.send(handleQueryResponseMQ);
      };
    
    function handleQueryResponseMQ(responseMQ) {
      if (responseMQ.isError()) {
       alert('Error in query: ' + responseMQ.getMessage() + ' ' + responseMQ.getDetailedMessage());
       return;
      }
  
    var options = {
          title: 'Milk Production',
          hAxis: {title: 'State', titleTextStyle: {color: 'red'}}
        };

    var data = responseMQ.getDataTable();
    var chartMQ = new google.visualization.ColumnChart(document.getElementById('chart_divMQ'));
    chartMQ.draw(data, options );
}

    </script>
  </head>
  <body>
  <h3>
Basic Column Chart Showing All Data</h3>
<div id="chart_divMQ" style="height: 500px; width: 900px;">
</div>
<a href="https://docs.google.com/a/yantrajaal.com/spreadsheet/ccc?key=0AhEX55Pfl1eedExUbS1xNzBuQVAyNDJTeG1weFQxbXc&amp;usp=drive_web#gid=1" target="_blank">Data Source</a>
  </body>
<br />



In the next post we will convert this into a Dashboard

Wednesday, 18 December 2013

6 Showing Addresses on a Google Map

In this example, we wish to show on a  the locations of certain schools in Calcutta whose addresses are known. We begin with a primary source of data and copy the same into a Google Docs spreadsheet. This base data is then copied into a another sheet for pre-processing. This activity is partially manual where we cut, copy and paste the data for 10 schools into one portion of the spreadsheet so that the school name and school address of the schools in question appear adjacent to each other -- in columns C, D of this sheet.

Converting addresses to latitude and longitude is known as GeoCoding and Google Maps provides APIs for this. However we have used a simple Google Apps Script adapted from one found in Amit Agarwals Programmer's Library to calculate the latitude and longitude corresponding to each school address.

Running this script ( the listing of which is given in this post)  generates the positions and these are visible in columns F and G of the pre-processing sheet.

The final, clean data consisting of the latitude, longitude and school name is now copied into the final GeoCodeData sheet for transmission to the HTML page that will display the map.

From here onward, we use the templates that Google provides for Map Visualisation with the exception that in this case our data is not hard coded into the HTML page but is being picked up from the spreadsheet.

The HTML code for this is shown in the post below. Note that we have specified the

  • spreadsheet - through the value of the key, that can be picked up from the URL
  • sheet - in this case sheet=GeoCodeData
  • range - B2:D11
  • there are no headers
  • we use columns B,C,D where B = lat, C= long and D is a text field, in this case school name


This is the map that is produced


We observe that the location of certain schools have not been shown correctly though they are by and large in the general area. This is because of a lack of precision in geocoding because Google could not identify the exact address and settled for a general area based perhaps on the name of the road or the PIN code. This can be manually improved by going to the real Google Map and zooming repeatedly until the address is visible and noting the precise lat/long of that address.

This is the GoogleScript code used in Google Docs to GeoCode addresses into lat/long positions

function pm_geocode_Addresses() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); 
  var locationInfo = sheet.getRange(2, 4, 10, 1).getValues();
  var geoResults, lat, lng;
 
  for (var i = 0; i < locationInfo.length; i++) {
    geoResults = Maps.newGeocoder().geocode(locationInfo[i]);
 
    // Get the latitude and longitude
    lat = geoResults.results[0].geometry.location.lat;
    lng = geoResults.results[0].geometry.location.lng;
    sheet.getRange(i+2, 6, 1, 1).setValue(lat);
    sheet.getRange(i+2, 7, 1, 1).setValue(lng);    
    Utilities.sleep(1000);    
  }
}


This is the HTML code that is embedded in this blog

<head>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["map"]});
      google.setOnLoadCallback(drawMapBU);
      function drawMapBU() {
        var query = new google.visualization.Query(
      'https://docs.google.com/a/yantrajaal.com/spreadsheet/ccc?key=xxxxxxxxxx&sheet=GeoCodeData&range=B2:D11&headers=0');
      query.setQuery('select B,C,D'); 
      query.send(handleQueryResponseBU);;
      
      function handleQueryResponseBU(response) {
       if (response.isError()) {
         alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
        return;
       }
 
      var data = response.getDataTable();
      var map = new google.visualization.Map(document.getElementById('map_divBU'));
      map.draw(data, {showTip: true});
       }     
      }
    </script>
  </head>
  <body>
    <div id="map_divBU" style="width: 600px; height: 500px"></div>
  </body>


For some reason, the map on this blog is in black and white even though on the normal HTML page the colours are showing properly. What can be reason for this ? If anyone knows, will appreciate a suggestion.