tag:blogger.com,1999:blog-63834768674374524162024-03-22T10:10:44.079+05:30VizualyseVizualyse is a repository of source code created while learning and experimenting with various tools and techniques of data visualisation. It is an outcome of the activities associated with the Business Analytics program at Praxis Business School, Calcutta. Please see the sidebar for various ways of navigating through this blog.Prithwishttp://www.blogger.com/profile/14023204360522864496noreply@blogger.comBlogger23125tag:blogger.com,1999:blog-6383476867437452416.post-38664096652163439772017-01-24T15:27:00.001+05:302017-06-29T16:49:50.306+05:30Geo Maps - with Usage of API key <head>
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type='text/javascript'>
google.load('visualization', '1', {'packages': ['geochart']});
google.setOnLoadCallback(drawMarkersMap02);
function drawMarkersMap02() {
var query = new google.visualization.Query(
'https://docs.google.com/a/yantrajaal.com/spreadsheet/ccc?key=0AhEX55Pfl1eedE5mUHN4QVRLNzdldEpwZnAyNy1abUE&sheet=CityWise2&range=B2:M23&headers=1');
query.setQuery('select B,D,E');
query.send(handleQueryResponse02);
};
function handleQueryResponse02(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var options = {
datalessRegionColor : 'FFFF99',
region: 'IN',
displayMode: 'markers',
colorAxis: {colors: ['green', 'blue']}
};
var data = response.getDataTable();
var chart = new google.visualization.GeoChart(document.getElementById('pm_div4'));
chart.draw(data, options );
}
</script>
</head>
<body>
<div id="pm_div4" style="width: 600px; height: 500px;"></div>
</body>Prithwishttp://www.blogger.com/profile/14023204360522864496noreply@blogger.com0tag:blogger.com,1999:blog-6383476867437452416.post-49689031211096735542015-05-28T07:24:00.000+05:302015-05-30T19:12:42.449+05:3018. googleVis - The best of R and GoogleCharts<div dir="ltr" style="text-align: left;" trbidi="on">
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.<br />
<br />
The resultant charts need to be viewed in a browser -- and the html code is available for embedding in websites like this. This <a href="https://docs.google.com/spreadsheets/d/1HMYFA8ahqZRuSxm7ZfYChsR6-5U0zax3y1Dd2DLeSdc/edit?usp=sharing" rel="nofollow" target="_blank">google docs spreadsheet </a>has some data on milk production in Indian states. It has been downloaded and used for these exercises<br />
<br />
Here is the code :<br />
<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono,Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code style="color: black; word-wrap: normal;">
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)
</code>
</pre>
<br />
and here is the chart that is generated by code printed out by the last print command<br />
-----------------
<!-- GeoChart generated in R 3.0.2 by googleVis 0.5.8 package -->
<!-- Thu May 28 07:18:10 2015 -->
<!-- jsHeader -->
<script type="text/javascript">
// jsData
function gvisDataGeoChartIDe315e03b5c4 () {
var data = new google.visualization.DataTable();
var datajson =
[
[
"Andhra Pradesh",
8925
],
[
"Arunachal Pradesh",
32
],
[
"Assam",
752
],
[
"Bihar",
5783
],
[
"Chattisgarh",
866
],
[
"Goa",
58
],
[
"Gujarat",
7911
],
[
"Haryana",
5442
],
[
"Himachal Pradesh",
1007
],
[
"Jammu & Kashmir",
1519
],
[
"Jharkhand",
1442
],
[
"Karnataka",
4244
],
[
"Kerala",
2253
],
[
"Madhya Pradesh",
6572
],
[
"Maharashtra",
7210
],
[
"Manipur",
78
],
[
"Meghalaya",
77
],
[
"Mizoram",
17
],
[
"Nagaland",
45
],
[
"Orissa",
1625
],
[
"Punjab",
9282
],
[
"Rajasthan",
11377
],
[
"Sikkim #",
42
],
[
"Tamil Nadu",
6540
],
[
"Tripura",
91
],
[
"Uttar Pradesh",
18861
],
[
"Uttarakhand",
1221
],
[
"West Bengal",
4087
],
[
"A&N Islands",
24
],
[
"Chandigarh",
47
],
[
"D.& N. Haveli #",
10
],
[
"Daman & Diu #",
1
],
[
"Delhi #",
445
],
[
"Lakshadweep",
2
],
[
"Puducherry",
46
]
];
data.addColumn('string','State');
data.addColumn('number','Total');
data.addRows(datajson);
return(data);
}
// jsDrawChart
function drawChartGeoChartIDe315e03b5c4() {
var data = gvisDataGeoChartIDe315e03b5c4();
var options = {};
options["width"] = 600;
options["height"] = 400;
options["region"] = "IN";
options["displayMode"] = "regions";
options["resolution"] = "provinces";
var chart = new google.visualization.GeoChart(
document.getElementById('GeoChartIDe315e03b5c4')
);
chart.draw(data,options);
}
// jsDisplayChart
(function() {
var pkgs = window.__gvisPackages = window.__gvisPackages || [];
var callbacks = window.__gvisCallbacks = window.__gvisCallbacks || [];
var chartid = "geochart";
// Manually see if chartid is in pkgs (not all browsers support Array.indexOf)
var i, newPackage = true;
for (i = 0; newPackage && i < pkgs.length; i++) {
if (pkgs[i] === chartid)
newPackage = false;
}
if (newPackage)
pkgs.push(chartid);
// Add the drawChart function to the global list of callbacks
callbacks.push(drawChartGeoChartIDe315e03b5c4);
})();
function displayChartGeoChartIDe315e03b5c4() {
var pkgs = window.__gvisPackages = window.__gvisPackages || [];
var callbacks = window.__gvisCallbacks = window.__gvisCallbacks || [];
window.clearTimeout(window.__gvisLoad);
// The timeout is set to 100 because otherwise the container div we are
// targeting might not be part of the document yet
window.__gvisLoad = setTimeout(function() {
var pkgCount = pkgs.length;
google.load("visualization", "1", { packages:pkgs, callback: function() {
if (pkgCount != pkgs.length) {
// Race condition where another setTimeout call snuck in after us; if
// that call added a package, we must not shift its callback
return;
}
while (callbacks.length > 0)
callbacks.shift()();
} });
}, 100);
}
// jsFooter
</script>
<!-- jsChart -->
<script src="https://www.google.com/jsapi?callback=displayChartGeoChartIDe315e03b5c4" type="text/javascript"></script>
<!-- divChart -->
<br />
<div id="GeoChartIDe315e03b5c4" style="height: 400; width: 600;">
</div>
<div>
Data: StateMilk • Chart ID: <a href="https://www.blogger.com/Chart_GeoChartIDe315e03b5c4.html">GeoChartIDe315e03b5c4</a> • <a href="https://github.com/mages/googleVis">googleVis-0.5.8</a><br />
<!-- htmlFooter -->
R version 3.0.2 (2013-09-25)
• <a href="https://developers.google.com/terms/">Google Terms of Use</a> • <a href="https://google-developers.appspot.com/chart/interactive/docs/gallery/geochart">Documentation and Data Policy</a>
<br />
-----------------
<br />
<br />
In addition to maps, you can also draw bar and column charts like with this code<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono,Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code style="color: black; word-wrap: normal;">
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)
</code>
</pre>
<br />
A complete list of sample code for all possible types of googleVis charts is available at <a href="http://cran.r-project.org/web/packages/googleVis/vignettes/googleVis_examples.html" rel="nofollow" target="_blank">on this page</a>. All the examples can be executed by running the demo program as explained at the top of the reference page.</div>
</div>
Prithwishttp://www.blogger.com/profile/14023204360522864496noreply@blogger.com2tag:blogger.com,1999:blog-6383476867437452416.post-50250434723189588052015-05-03T19:32:00.000+05:302015-05-30T19:12:28.823+05:3017 Plotting Addresses on Google Maps using R and R GoogleMaps<div dir="ltr" style="text-align: left;" trbidi="on">
In an <a href="http://visual.yantrajaal.com/2013/12/showing-addresses-on-google-map.html" target="_blank">earlier post</a>, 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.<br />
<br />
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.<br />
<br />
Please see the code here :<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono,Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code style="color: black; word-wrap: normal;">#
# 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)</code>
</pre>
<br />
Couple of observations :<br />
<br />
<ol>
<li>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 <a href="https://github.com/prithwis/WebScraper/blob/master/CalcuttaSchools.tsv" rel="nofollow" target="_blank">github</a>.</li>
<li>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 <a href="https://github.com/prithwis/WebScraper/blob/master/SchoolDataScraper0.py" rel="nofollow" target="_blank">github</a>.</li>
<li>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.</li>
<li>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</li>
<li>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</li>
</ol>
<div>
Here are two maps generated by this program</div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg3O_J2k9JqVRZ2qL0kLNehtBqwdguUrx6Xusea2K6QhU1jdGFTtMconGmDO2aWd8-TM02UzKAWnOnwE_qkepTidymGcJvqb8IR-ZAKz6RuPaeRrlXuPd0w9xVGJAHbMK0lE0qzAnaZ/s1600/MapSchools-801.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg3O_J2k9JqVRZ2qL0kLNehtBqwdguUrx6Xusea2K6QhU1jdGFTtMconGmDO2aWd8-TM02UzKAWnOnwE_qkepTidymGcJvqb8IR-ZAKz6RuPaeRrlXuPd0w9xVGJAHbMK0lE0qzAnaZ/s1600/MapSchools-801.png" /></a></div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi8nGP7ZI97gDovYdFgZt-9DtVSrF6tN9vk9s5PZAideiKFII4NWQSN8E_stXS-XuDDrgkiTx8VLLLBzXckNyqBuwlyhz8TlWtMjtp4oU-0EwMkxyqy8tBYChjD7l4gVuGytMdub6ws/s1600/MapSchools-802.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi8nGP7ZI97gDovYdFgZt-9DtVSrF6tN9vk9s5PZAideiKFII4NWQSN8E_stXS-XuDDrgkiTx8VLLLBzXckNyqBuwlyhz8TlWtMjtp4oU-0EwMkxyqy8tBYChjD7l4gVuGytMdub6ws/s1600/MapSchools-802.png" /></a></div>
<div>
<br /></div>
<br />
<br /></div>
Prithwishttp://www.blogger.com/profile/11940658684717969663noreply@blogger.com3tag:blogger.com,1999:blog-6383476867437452416.post-56993902565395529542015-05-02T09:18:00.001+05:302015-09-23T11:33:17.150+05:3016. Using R for Maps of India - state, district, taluka level maps<div dir="ltr" style="text-align: left;" trbidi="on">
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.<br />
<br />
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 <a href="http://gadm.org/" rel="nofollow" target="_blank">Global Administrative Areas or gadm.org</a>. <a href="http://gadm.org/country" rel="nofollow" target="_blank">Country level files</a> 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.<br />
<br />
Working with R, we will need two R packages :<br />
<br />
# Load required libraries<br />
library(sp)<br />
library(RColorBrewer)<br />
<br />
Assuming that the downloaded RData file is located in the R working directory, the following code will generate a basic India showing the states<br />
<br />
# load level 1 india data downloaded from http://gadm.org/country<br />
load("IND_adm1.RData")<br />
ind1 = gadm<br />
<br />
# simple map of India with states drawn<br />
# <span style="color: red;">unfortunately, Kashmir will get truncated</span><br />
spplot(ind1, "NAME_1", scales=list(draw=T), colorkey=F, main="India")<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhcpIJEYQA6Eaj9_d3PL1jmFMYFidQ1sYzr01mmms5FZcHPczbltMfAe3ZjFYRiQIxAcLFUVc6ws6gQX7znOr51_Mv3NpR8vrWtjWhZKTACcIVxvzMSPqnJdl_OQw7hY7A52kYxga-y/s1600/Map1a.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="640" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhcpIJEYQA6Eaj9_d3PL1jmFMYFidQ1sYzr01mmms5FZcHPczbltMfAe3ZjFYRiQIxAcLFUVc6ws6gQX7znOr51_Mv3NpR8vrWtjWhZKTACcIVxvzMSPqnJdl_OQw7hY7A52kYxga-y/s1600/Map1a.png" width="569" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
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 <a href="http://gis.stackexchange.com/questions/80565/plotting-a-map-of-new-zealand-with-regional-boundaries-in-r" rel="nofollow" target="_blank">gis.stackexchange</a> ]</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both;">
# map of India with states coloured with an arbitrary fake data</div>
<div class="separator" style="clear: both;">
ind1$NAME_1 = as.factor(ind1$NAME_1)</div>
<div class="separator" style="clear: both;">
ind1$fake.data = runif(length(ind1$NAME_1))</div>
<div class="separator" style="clear: both;">
spplot(ind1,"NAME_1", col.regions=rgb(0,ind1$fake.data,0), colorkey=T, main="Indian States")</div>
<div class="separator" style="clear: both;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjULbsqk7G34FGHdUmQjUFrtzyILLdfBJ8E32hZTsbmAXzOqAueNFhEZH5ckaYbVQylLJ_xHYqPxUmapEzjpbL0_cX3bwo1q6wG1olPZp3sSbyEPFXFALaSc-3e-PNFf1ziO9KkfJnI/s1600/Map2.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="640" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjULbsqk7G34FGHdUmQjUFrtzyILLdfBJ8E32hZTsbmAXzOqAueNFhEZH5ckaYbVQylLJ_xHYqPxUmapEzjpbL0_cX3bwo1q6wG1olPZp3sSbyEPFXFALaSc-3e-PNFf1ziO9KkfJnI/s1600/Map2.png" width="569" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
Now let us draw the map of any one state. First check the spelling of each state by listing the states:</div>
<div class="separator" style="clear: both; text-align: left;">
ind1$NAME_1</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
and then executing these commands :</div>
<div class="separator" style="clear: both;">
# map of West Bengal ( or any other state )</div>
<div class="separator" style="clear: both;">
wb1 = (ind1[ind1$NAME_1=="West Bengal",])</div>
<div class="separator" style="clear: both;">
spplot(wb1,"NAME_1", col.regions=rgb(0,0,1), main = "West Bengal, India",scales=list(draw=T), colorkey =F)</div>
<div class="separator" style="clear: both;">
<br /></div>
<div class="separator" style="clear: both;">
# map of Karnataka ( or any other state )</div>
<div class="separator" style="clear: both;">
kt1 = (ind1[ind1$NAME_1=="Karnataka",])</div>
<div class="separator" style="clear: both;">
spplot(kt1,"NAME_1", col.regions=rgb(0,1,0), main = "Karnataka, India",scales=list(draw=T), colorkey =F)</div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh8PBB4KfE2GoqQ44uk9vUgs_aFbJJvbCn2SPg_ItQmHniMu6NQcPA-7gL315VhMryIBvSBvxoMiXhs1SiJF_tYdYzeX8vmNuGG3_Lt2GIzlsad51LBIv_HKYsXnXz3Q39DzEIlBEYj/s1600/Map3.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="640" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh8PBB4KfE2GoqQ44uk9vUgs_aFbJJvbCn2SPg_ItQmHniMu6NQcPA-7gL315VhMryIBvSBvxoMiXhs1SiJF_tYdYzeX8vmNuGG3_Lt2GIzlsad51LBIv_HKYsXnXz3Q39DzEIlBEYj/s1600/Map3.png" width="569" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
If we want to get and map district level data then we need to use the level 2 data as follows :</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both;">
# load level 2 india data downloaded from http://gadm.org/country</div>
<div class="separator" style="clear: both;">
load("IND_adm2.RData")</div>
<div class="separator" style="clear: both;">
ind2 = gadm</div>
<div class="separator" style="clear: both;">
<br /></div>
<div class="separator" style="clear: both;">
and then plot the various districts as</div>
<div class="separator" style="clear: both;">
<br /></div>
<div class="separator" style="clear: both;">
# plotting districts of a State, in this case West Bengal</div>
<div class="separator" style="clear: both;">
wb2 = (ind2[ind2$NAME_1=="West Bengal",])</div>
<div class="separator" style="clear: both;">
spplot(wb2,"NAME_1", main = "West Bengal Districts", colorkey =F)</div>
<div class="separator" style="clear: both;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiCmFdb7UEQGtuFpA0VvP-gmCyLwJooAANCd-upxuUQnNqwt0FMt1eZZsYxP3K88bP9fQq2TrA_cXg1xxa-9QG8uJdjM7xxJUsmI6K8V1RwmcQL3gXcL0ga00ol_ls_O3alztgBhYk0/s1600/Map6.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="640" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiCmFdb7UEQGtuFpA0VvP-gmCyLwJooAANCd-upxuUQnNqwt0FMt1eZZsYxP3K88bP9fQq2TrA_cXg1xxa-9QG8uJdjM7xxJUsmI6K8V1RwmcQL3gXcL0ga00ol_ls_O3alztgBhYk0/s1600/Map6.png" width="569" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
To identify each district with a beautiful colour we can use the following commands :</div>
<div class="separator" style="clear: both;">
# colouring the districts with rainbow of colours</div>
<div class="separator" style="clear: both;">
wb2$NAME_2 = as.factor(wb2$NAME_2)</div>
<div class="separator" style="clear: both;">
col = rainbow(length(levels(wb2$NAME_2)))</div>
<div class="separator" style="clear: both;">
spplot(wb2,"NAME_2", col.regions=col, colorkey=T)</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhAhrNOKZ04PiPq7l2y0LYrb8aII7LeA2Kb8jQ8-h2x4erjth5a58CUkLTs9ngPjF4YmLXDBH8NrK1xv7FYF8OF8KiU8DGgUlHW7B4FELaW212fagUNOmqyGujF9uA3sScodmNmVUqw/s1600/Map7.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="640" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhAhrNOKZ04PiPq7l2y0LYrb8aII7LeA2Kb8jQ8-h2x4erjth5a58CUkLTs9ngPjF4YmLXDBH8NrK1xv7FYF8OF8KiU8DGgUlHW7B4FELaW212fagUNOmqyGujF9uA3sScodmNmVUqw/s1600/Map7.png" width="569" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
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 :</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both;">
# colouring the districts with some simulated, fake data</div>
<div class="separator" style="clear: both;">
wb2$NAME_2 = as.factor(wb2$NAME_2)</div>
<div class="separator" style="clear: both;">
wb2$fake.data = runif(length(wb2$NAME_1)) </div>
<div class="separator" style="clear: both;">
spplot(wb2,"NAME_2", col.regions=rgb(0,wb2$fake.data, 0), colorkey=T)</div>
<div class="separator" style="clear: both;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgFHaAHRGm3XU2j26U3a-gaiiQ2VvlcXkfmH7YsSRbqY6T56ZDWJ7NKb0ngsXA8T-BeYLPh_X_YYfltJELuoE5eZClxcHFW3gvgaV0UAzUJVrbcVB-XwbhH1kTHAyl09zNpNHXbIunA/s1600/Map8.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="640" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgFHaAHRGm3XU2j26U3a-gaiiQ2VvlcXkfmH7YsSRbqY6T56ZDWJ7NKb0ngsXA8T-BeYLPh_X_YYfltJELuoE5eZClxcHFW3gvgaV0UAzUJVrbcVB-XwbhH1kTHAyl09zNpNHXbIunA/s1600/Map8.png" width="569" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
But we can be even more clever by allocating certain shades of colour to certain ranges of data as with this code, adapted from<a href="https://ryouready.wordpress.com/2009/11/16/infomaps-using-r-visualizing-german-unemployment-rates-by-color-on-a-map/" rel="nofollow" target="_blank"> this website</a></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both;">
# colouring the districts with range of colours</div>
<div class="separator" style="clear: both;">
col_no = as.factor(as.numeric(cut(wb2$fake.data, c(0,0.2,0.4,0.6,0.8,1))))</div>
<div class="separator" style="clear: both;">
levels(col_no) = c("<20%", "20-40%", "40-60%","60-80%", ">80%")</div>
<div class="separator" style="clear: both;">
wb2$col_no = col_no</div>
<div class="separator" style="clear: both;">
myPalette = brewer.pal(5,"Greens")</div>
<div class="separator" style="clear: both;">
spplot(wb2, "col_no", col=grey(.9), col.regions=myPalette, main="District Wise Data")</div>
<div class="separator" style="clear: both;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhFp0ntMA_Q35YMVM4vbc7KTQLka6A_U7VVlOo3oNKFNYSijQbjQexa5rcVFeZrWwxS-5VgKQHaI1u30FsiWrp9MZ2pxKX3ojG85xCBcOq5Mug2dNP4bfoKqdeuw7Gqu8FJsKtlUnQx/s1600/Map9.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="640" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhFp0ntMA_Q35YMVM4vbc7KTQLka6A_U7VVlOo3oNKFNYSijQbjQexa5rcVFeZrWwxS-5VgKQHaI1u30FsiWrp9MZ2pxKX3ojG85xCBcOq5Mug2dNP4bfoKqdeuw7Gqu8FJsKtlUnQx/s1600/Map9.png" width="570" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
To move to the district, sub-division ( or taluk) level we need to use the level three data file :</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both;">
# load level 3 india data downloaded from http://gadm.org/country</div>
<div class="separator" style="clear: both;">
load("IND_adm3.RData")</div>
<div class="separator" style="clear: both;">
ind3 = gadm</div>
<div class="separator" style="clear: both;">
<br /></div>
<div class="separator" style="clear: both;">
# extracting data for West Bengal</div>
<div class="separator" style="clear: both;">
wb3 = (ind3[ind3$NAME_1=="West Bengal",])</div>
<div class="separator" style="clear: both;">
<br /></div>
<div class="separator" style="clear: both;">
and then plot the subdivision or taluk level map as follows :</div>
<div class="separator" style="clear: both;">
<br /></div>
<div class="separator" style="clear: both;">
#plotting districts and sub-divisions / taluk</div>
<div class="separator" style="clear: both;">
wb3$NAME_3 = as.factor(wb3$NAME_3)</div>
<div class="separator" style="clear: both;">
col = rainbow(length(levels(wb3$NAME_3)))</div>
<div class="separator" style="clear: both;">
spplot(wb3,"NAME_3", main = "Taluk, District - West Bengal", colorkey=T,col.regions=col,scales=list(draw=T))</div>
<div class="separator" style="clear: both;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgAMLr7zn9unUwVBP4OpGLLfzwEtM6CLjP4Gk7V5KLEs9VaBAaqDzV1znC7O1EjAPqBPbjC8pkCJZSxiWHNhSYJXAC5UBj89BBji593fFC_FxcUrAfye1cZPbMrADVfw2ji_JALsXRV/s1600/Map10.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="640" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgAMLr7zn9unUwVBP4OpGLLfzwEtM6CLjP4Gk7V5KLEs9VaBAaqDzV1znC7O1EjAPqBPbjC8pkCJZSxiWHNhSYJXAC5UBj89BBji593fFC_FxcUrAfye1cZPbMrADVfw2ji_JALsXRV/s1600/Map10.png" width="570" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
Now let us get a map of the district - North 24 Parganas. Make sure that the name is spelt correctly.</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both;">
# get map for "North 24 Parganas District"</div>
<div class="separator" style="clear: both;">
wb3 = (ind3[ind3$NAME_1=="West Bengal",])</div>
<div class="separator" style="clear: both;">
n24pgns3 = (wb3[wb3$NAME_2=="North 24 Parganas",])</div>
<div class="separator" style="clear: both;">
spplot(n24pgns3,"NAME_3", colorkey =F, scales=list(draw=T), main = "24 Pgns (N) West Bengal")</div>
<div class="separator" style="clear: both;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh81JyZFHrUT_tG8QoL42cjrSBkNputWNrU2t2za0IWr084PqvBfdHEh54SMDqV0DPTfxgyJwz_DDql9IIChnlxzBoPF9QK0zD9YYQeGVvHvEP16a4DzrRz6ILOM0KutoL_092SqXZk/s1600/Map11.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="640" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh81JyZFHrUT_tG8QoL42cjrSBkNputWNrU2t2za0IWr084PqvBfdHEh54SMDqV0DPTfxgyJwz_DDql9IIChnlxzBoPF9QK0zD9YYQeGVvHvEP16a4DzrRz6ILOM0KutoL_092SqXZk/s1600/Map11.png" width="570" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
and within North 24 Parganas district, we can go down to the Basirhat Subdivision ( Taluk) and draw the map as follows: </div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both;">
# now draw the map of Basirhat subdivision</div>
<div class="separator" style="clear: both;">
# recreate North 24 Parganas data</div>
<div class="separator" style="clear: both;">
n24pgns3 = (wb3[wb3$NAME_2=="North 24 Parganas",])</div>
<div class="separator" style="clear: both;">
basirhat3 = (n24pgns3[n24pgns3$NAME_3=="Basirhat",])</div>
<div class="separator" style="clear: both;">
spplot(basirhat3,"NAME_3", colorkey =F, scales=list(draw=T), main = "Basirhat,24 Pgns (N) West Bengal")</div>
<div class="separator" style="clear: both;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhAwXFec5YSgo1Sx5oQpS_mIVVr_ped5fuc69Afiexwd4mTRg0TnEQsPb9gAr9zrP-AnjuplZELp_yfBUltVlygw1gaDm6fcsRiE-dQGejHN4Q8LTlHERTb-rOWHSWI6y0R3uJJTHNS/s1600/Map12.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="640" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhAwXFec5YSgo1Sx5oQpS_mIVVr_ped5fuc69Afiexwd4mTRg0TnEQsPb9gAr9zrP-AnjuplZELp_yfBUltVlygw1gaDm6fcsRiE-dQGejHN4Q8LTlHERTb-rOWHSWI6y0R3uJJTHNS/s1600/Map12.png" width="570" /></a></div>
<div class="separator" style="clear: both;">
<br /></div>
<div class="separator" style="clear: both;">
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.</div>
<div class="separator" style="clear: both;">
<br /></div>
<div class="separator" style="clear: both;">
# zoomed in data</div>
<div class="separator" style="clear: both;">
wb2 = (ind2[ind2$NAME_1=="West Bengal",])</div>
<div class="separator" style="clear: both;">
wb2$NAME_2 = as.factor(wb2$NAME_2)</div>
<div class="separator" style="clear: both;">
col = rainbow(length(levels(wb2$NAME_2)))</div>
<div class="separator" style="clear: both;">
spplot(wb2,"NAME_2", col.regions=col,scales=list(draw=T),ylim=c(23.5,25),xlim=c(87,89), colorkey=T)</div>
<div class="separator" style="clear: both;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi-UxPDNmON2ndgpcZIv7HIyNqwk6NSOblY41NdwmeKh6z3D_HWrbRHH8hzU_zQPYnRCZZcbUWETFf81x8Vqn0sZZGNIikKG4odprOzekfEYogWYpfTdSlF9_739uEef3REIs46Z2zn/s1600/Map13.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="640" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi-UxPDNmON2ndgpcZIv7HIyNqwk6NSOblY41NdwmeKh6z3D_HWrbRHH8hzU_zQPYnRCZZcbUWETFf81x8Vqn0sZZGNIikKG4odprOzekfEYogWYpfTdSlF9_739uEef3REIs46Z2zn/s1600/Map13.png" width="570" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both;">
<br /></div>
<div class="separator" style="clear: both;">
With this it should be possible to draw any map of India. For more comprehensive examples of such maps, please see <a href="http://rstudio-pubs-static.s3.amazonaws.com/6772_441847b522584d1095daddc2677e4ddb.html" rel="nofollow" target="_blank">this page</a>.</div>
<div>
<br /></div>
<hr />
Here is the entire code
<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono,Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code style="color: black; word-wrap: normal;">
========================================
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)
</code>
</pre>
<br />
<div class="separator" style="clear: both; text-align: left;">
PostScript</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
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 </div>
<div class="separator" style="clear: both; text-align: left;">
</div>
<ol>
<li>a function for geocoding place names into lon, lat values</li>
<li>usage of the sp.layout option to place markers and texts on the map.</li>
</ol>
<div>
This has now been done, and you can see the three towns in West Bengal marked as follows</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEipH5N_3rouhOIgQTr6J1FtAiJ5KBL0Da7mLfFsMoo0DyaX__K5P0C7fhMdmy9kQ_sR8znaIeZUyXoxuHGVGSOT0gkdVFCwyYjWzFtPOzRrZ9MSPgTzKXU3WoVp4R6Ho3dVZ4TeopSY/s1600/MapPointing001.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="640" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEipH5N_3rouhOIgQTr6J1FtAiJ5KBL0Da7mLfFsMoo0DyaX__K5P0C7fhMdmy9kQ_sR8znaIeZUyXoxuHGVGSOT0gkdVFCwyYjWzFtPOzRrZ9MSPgTzKXU3WoVp4R6Ho3dVZ4TeopSY/s640/MapPointing001.png" width="570" /></a></div>
<div>
<br /></div>
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono,Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code style="color: black; word-wrap: normal;">
# 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))
</code>
</pre>
<br />
to change plot symbols look at <a href="http://www.statmethods.net/advgraphs/parameters.html">http://www.statmethods.net/advgraphs/parameters.html</a></div>
Prithwishttp://www.blogger.com/profile/11940658684717969663noreply@blogger.com13tag:blogger.com,1999:blog-6383476867437452416.post-4919758486381448432014-06-16T20:33:00.003+05:302014-06-16T20:36:04.353+05:30Ritvvij Parikh's talk on Visualization, Data Journalism<div dir="ltr" style="text-align: left;" trbidi="on">
<iframe width="560" height="315" src="//www.youtube.com/embed/3gr6rxRYIIo" frameborder="0" allowfullscreen></iframe>
<br /></div>Prithwishttp://www.blogger.com/profile/14023204360522864496noreply@blogger.com0tag:blogger.com,1999:blog-6383476867437452416.post-24512096695509758502014-04-23T10:12:00.003+05:302014-04-23T21:23:04.661+05:3015. Motion Charts <div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
Watch this video<br />
<iframe allowfullscreen="" frameborder="0" height="315" src="//www.youtube.com/embed/jbkSRLYSojo" width="560"></iframe> <br />
Then make your own motion charts by <a href="https://developers.google.com/chart/interactive/docs/gallery/motionchart?csw=1" target="_blank">either writing code</a>, or better still simply using <a href="http://www.gapminder.org/upload-data/motion-chart/#.U1dCQPmSxnw" target="_blank">Google Docs</a>.</div>
<hr />
<iframe frameborder="0" height="371" scrolling="no" seamless="" src="//docs.google.com/a/yantrajaal.com/spreadsheets/d/13cet4B9OVSXYTtBGs_Y0bLhjJLwHj6EtvkOqI6SKUhM/gviz/chartiframe?oid=1331052409" width="600"></iframe>
<br />
<hr />
was created with data on Tata Group stock prices from <a href="http://www.quandl.com/search/Tata%20Steel?page=1&source_ids=33" target="_blank">Quandl</a> and residing on this <a href="https://docs.google.com/spreadsheets/d/13cet4B9OVSXYTtBGs_Y0bLhjJLwHj6EtvkOqI6SKUhM/edit?usp=sharing" target="_blank">Google Docs sheet</a></div>
Prithwishttp://www.blogger.com/profile/14023204360522864496noreply@blogger.com0tag:blogger.com,1999:blog-6383476867437452416.post-34438779581771328122014-03-03T11:47:00.001+05:302014-03-03T11:50:33.438+05:3014. IBM Many Eyes<div dir="ltr" style="text-align: left;" trbidi="on">
<a href="http://www-958.ibm.com/software/data/cognos/manyeyes/" target="_blank">Many Eyes</a> is another excellent tool that allows you to create very nice vizualizations that you can publish like this.<br />
----<br />
<script src="http://www-958.ibm.com/me/visualizations/887eb904a29a11e39c5f000255111976/comments/88876658a29a11e39c5f000255111976.js?width=425&height=350" type="text/javascript"></script>
---<br />
<br />
This<a href="http://www-958.ibm.com/software/data/cognos/manyeyes/visualizations/vivekanda-chicago" target="_blank"> visualisation</a> was done by following <a href="http://blended21.pbworks.com/f/manyeyes+tutorial.pdf" target="_blank">this tutorial </a>and using text of Vivekananda's at Chicago taken from <a href="http://hinduism.about.com/od/vivekananda/a/vivekananda_speeches.htm" target="_blank">this website</a>. You can also explore other types of visualisations using the same data.</div>
Prithwishttp://www.blogger.com/profile/14023204360522864496noreply@blogger.com0tag:blogger.com,1999:blog-6383476867437452416.post-29329132200496139442014-02-19T17:30:00.002+05:302014-03-03T11:12:12.180+05:3013. Google Fusion Tables - Tutorial<div dir="ltr" style="text-align: left;" trbidi="on">
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<a href="https://docs.google.com/document/d/1s0U6Rskvf0QEbEQkkcGf6fsacdp86-D4nY31yVsM8tQ/edit?usp=sharing" target="_blank"> tutorial</a>.<br />
<br />
<iframe frameborder="no" height="300" scrolling="no" src="https://www.google.com/fusiontables/embedviz?q=select+col6+from+15O1BUYhVCLfIcnxZhIewQywejGpcI2E_HcvsLxY&viz=MAP&h=false&lat=25.918195961544914&lng=82.95550000000003&t=1&z=5&l=col6&y=2&tmplt=2&hml=TWO_COL_LAT_LNG" width="500"></iframe>
Here is <a href="http://www.smalldatajournalism.com/projects/one-offs/mapping-with-fusion-tables/" rel="nofollow" target="_blank">another tutorial</a> that shows how to turn spreadsheets into interactive maps, and here is a a<a href="https://sites.google.com/site/fusiontablestalks/talks/fusion-tables-where-2-0-workshop" rel="nofollow" target="_blank"> workshop</a> on Google Fusion Tables.</div>
Prithwishttp://www.blogger.com/profile/14023204360522864496noreply@blogger.com0tag:blogger.com,1999:blog-6383476867437452416.post-82816944281358911332014-02-13T15:06:00.001+05:302016-01-06T08:51:47.758+05:3012 Tableau - Getting Started<div dir="ltr" style="text-align: left;" trbidi="on">
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<a href="https://www.tableausoftware.com/public/download" target="_blank"> free public version that you can download</a>. To get started with Tableau, you can try out<a href="http://www.peteraldhous.com/CAR/tableau_demo.pdf" target="_blank"> this tutorial</a> 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 !<br />
<script src="http://public.tableausoftware.com/javascripts/api/viz_v1.js" type="text/javascript"></script><br />
<div class="tableauPlaceholder" style="height: 628px; width: 800px;">
<noscript><a href='#'><img alt=' ' src='http://public.tableausoftware.com/static/images/2N/2NM2BSF3G/1_rss.png' style='border: none' /></a></noscript><object class="tableauViz" height="628" style="display: none;" width="800"><param name='host_url' value='http%3A%2F%2Fpublic.tableausoftware.com%2F' /> <param name='path' value='shared/2NM2BSF3G' /> <param name='toolbar' value='yes' /><param name='static_image' value='http://public.tableausoftware.com/static/images/2N/2NM2BSF3G/1.png' /> <param name='animate_transition' value='yes' /><param name='display_static_image' value='yes' /><param name='display_spinner' value='yes' /><param name='display_overlay' value='yes' /><param name='display_count' value='yes' /></object></div>
<div style="color: black; font: normal 8pt verdana,helvetica,arial,sans-serif; height: 22px; padding: 0px 10px 0px 0px; width: 1308px;">
<div style="float: right; padding-right: 8px;">
<a href="http://www.tableausoftware.com/public/about-tableau-products?ref=http://public.tableausoftware.com/shared/2NM2BSF3G" target="_blank">Learn About Tableau</a></div>
</div>
<br />
or this <br />
<script src="http://public.tableausoftware.com/javascripts/api/viz_v1.js" type="text/javascript"></script><br />
<div class="tableauPlaceholder" style="height: 628px; width: 800px;">
<noscript><a href='#'><img alt=' ' src='http://public.tableausoftware.com/static/images/4J/4J6FZG76R/1_rss.png' style='border: none' /></a></noscript><object class="tableauViz" height="628" style="display: none;" width="800"><param name='host_url' value='http%3A%2F%2Fpublic.tableausoftware.com%2F' /> <param name='path' value='shared/4J6FZG76R' /> <param name='toolbar' value='yes' /><param name='static_image' value='http://public.tableausoftware.com/static/images/4J/4J6FZG76R/1.png' /> <param name='animate_transition' value='yes' /><param name='display_static_image' value='yes' /><param name='display_spinner' value='yes' /><param name='display_overlay' value='yes' /><param name='display_count' value='yes' /></object></div>
<div style="color: black; font: normal 8pt verdana,helvetica,arial,sans-serif; height: 22px; padding: 0px 10px 0px 0px; width: 1308px;">
<div style="float: right; padding-right: 8px;">
<a href="http://www.tableausoftware.com/public/about-tableau-products?ref=http://public.tableausoftware.com/shared/4J6FZG76R" target="_blank">Learn About Tableau</a></div>
</div>
Here are some more relevent resources<br />
1. A set of <a href="https://www.tableausoftware.com/public/community/sample-data-sets" rel="nofollow" target="_blank">data files</a> that you can practice with.<br />
2. A<a href="http://www.tableausoftware.com/beginners-data-visualization" rel="nofollow" target="_blank"> tutorial</a> with good data from General Social Survey<br />
3. A <a href="http://downloads.tableausoftware.com/quickstart/main-guides/desktop_getstarted6.0.pdf" rel="nofollow" target="_blank">quick start guide </a>with corresponding data from <a href="http://community.tableausoftware.com/docs/DOC-1236" rel="nofollow" target="_blank">Super Store</a>.<br />
4. A white paper from Tableau on <a href="https://drive.google.com/file/d/0B6awrNPy9RHoUk9oZnRNMDdHb0U/edit?usp=sharing" target="_blank">Which Chart is Right for You</a> !<br />
New Resources added in Jan 2016<br />
5. <a href="http://tekslate.com/tutorials/tableau/" target="_blank">Tekslate Tutorial on Tableau</a> - including interview questions<br />
6. <a href="http://www.analyticsvidhya.com/learning-paths-data-science-business-analytics-business-intelligence-big-data/tableau-learning-path/" target="_blank">Analytics Vidhya Introduction to Tableau</a><br />
7. <a href="http://www.mulinblog.com/annotated-tableau-public-tutorial-video-a-quick-start-guide-for-instructors-and-first-timers/" target="_blank">MuLin Tutorial</a> -- quite nice<br />
<br /></div>
Prithwishttp://www.blogger.com/profile/14023204360522864496noreply@blogger.com1tag:blogger.com,1999:blog-6383476867437452416.post-72071643198785175212013-12-31T19:54:00.000+05:302017-06-29T16:36:19.200+05:3011 RIL stock data from Quandl - Filtered on a range of dates<div dir="ltr" style="text-align: left;" trbidi="on">
This is an improvement on the chart shown in the <a href="http://vizualyse.blogspot.in/2013/12/plotting-nse-stock-price-data-from.html" target="_blank">previous post</a> where NSE data was picked up in CSV format from <a href="http://www.quandl.com/" target="_blank">Quandl - an excellent source of global timeseries data -- </a>and shown in a candlestick format. Since the data that we are plotting this time, <a href="http://www.quandl.com/NSE-National-Stock-Exchange-of-India/RELIANCE-Reliance-Industries-Limited" target="_blank">Reliance share prices</a>, goes back a long time. We will be using a <a href="https://developers.google.com/chart/interactive/docs/gallery/controls#chartrangefilter" target="_blank">RangeFilter to choose the start and end dates </a>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 <a href="http://jsfiddle.net/asgallant/8RFsB/1/" target="_blank">ASGALLANT</a>.The final chart is seen on <a href="http://prithwis.x10.bz/charts/vzl-quandl-rangefilter.html" target="_blank">this html page</a> and also in this blog page.<br />
<hr />
<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=MspdKdpirBQzxqZpxdov&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>
<br />
<hr />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono,Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code style="color: black; word-wrap: normal;">
<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>
</code><code style="color: black; word-wrap: normal;"><code style="color: black; word-wrap: normal;"><!--</code> <script src="https://jquery-csv.googlecode.com/files/jquery.csv-0.71.js"></script> </code><code style="color: black; word-wrap: normal;"><code style="color: black; word-wrap: normal;">--></code>
<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>
</code>
</pre>
<hr />
an <a href="http://vizualyse.blogspot.in/2013/12/creating-dashboard-part-ii.html" target="_blank">earlier post on dashboards </a>also talks about filters in some detail. however the code is possibly cleaner here.</div>
Prithwishttp://www.blogger.com/profile/11940658684717969663noreply@blogger.com1Santiniketan, West Bengal 731204, India23.68 87.680000000000064-1.8420345000000005 46.371406000000064 49.202034499999996 128.98859400000006tag:blogger.com,1999:blog-6383476867437452416.post-87727791746979826182013-12-29T18:47:00.002+05:302017-06-29T16:23:10.325+05:3010 Plotting NSE stock price data from Quandl<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<a href="http://www.quandl.com/" target="_blank">Quandl</a> 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 <a href="http://www.quandl.com/NSE-National-Stock-Exchange-of-India/TATASTEEL-Tata-Steel-Limited" target="_blank">here</a>. We will use this data to plot a <a href="https://developers.google.com/chart/interactive/docs/gallery/candlestickchart" target="_blank">Google Candlestick chart </a>that shows open, close, high, low data for the Tata Steel stock both in a <a href="http://prithwis.x10.bz/charts/vzl-quandlNSE.html" target="_blank">regular HTML page</a> and in the blog below.</div>
<hr />
<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=MspdKdpirBQzxqZpxdov&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="height: 500px; width: 900px;">
</div>
</body>
<br />
<hr />
There are couple of interesting things in the following code that are interesting to know about.<br />
<br />
<ul style="text-align: left;">
<li>While pulling the CSV data from Quandl, you can specify the start/end dates and the level of aggregation, that is daily, weekly, monthly</li>
<li>Google Candlestick charts expect the data to be in <a href="https://developers.google.com/chart/interactive/docs/gallery/candlestickchart" target="_blank">a certain order</a>. 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</li>
<li>This view and not the data is used to draw the chart</li>
</ul>
<br />
<hr />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono,Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code style="color: black; word-wrap: normal;">
<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> -->
</code><code style="color: black; word-wrap: normal;"><code style="color: black; word-wrap: normal;"><!--</code> <script src="https://jquery-csv.googlecode.com/files/jquery.csv-0.71.js"></script> </code><code style="color: black; word-wrap: normal;"><code style="color: black; word-wrap: normal;">--></code>
<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>
</code>
</pre>
<br />
<hr />
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 href="https://developers.google.com/chart/interactive/docs/gallery/controls#controlwrapperobject" target="_blank"> a control</a> so that you can specify the dates of your data rather than hardcoding the same into the java script.</div>
Prithwishttp://www.blogger.com/profile/14023204360522864496noreply@blogger.com0tag:blogger.com,1999:blog-6383476867437452416.post-65860318458098288252013-12-23T19:21:00.001+05:302017-06-29T16:31:21.480+05:309 Interactive Dashboard with Google Charts with external CSV data<div dir="ltr" style="text-align: left;" trbidi="on">
As an extension of the<a href="http://vizualyse.blogspot.in/2013/12/google-charts-from-public-csv-datasets.html" target="_blank"> previous post</a> where we used to data in CSV format available from an externally hosted source like <a href="http://www.quandl.com/" target="_blank">Quandl</a> to draw charts, we now see to inject a measure of interactivity into the same chart. The original CSV file containing data on <a href="http://www.quandl.com/MOSPI-Ministry-of-Statistics-India/EDU_INST_SCHOOL_EXPENDTR_29_1-EDUCATIONAL-INSTITUTIONS-SCHOOLS-AND-EXPENDITURE-INDIA" target="_blank">education in India </a>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<a href="http://prithwis.x10.bz/charts/vzl-csv-quandl002-choice.html" target="_blank"> an HTML page</a> or in this blog. This example is based on the tutorial given in <a href="http://economistry.com/2013/07/easy-data-visualization-with-google-charts-and-a-csv/" target="_blank">Economistry</a>.<br />
<br />
<hr />
<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=MspdKdpirBQzxqZpxdov&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>
<br />
<hr />
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.<br />
<hr />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono,Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code style="color: black; word-wrap: normal;">
<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>
</code><code style="color: black; word-wrap: normal;"><code style="color: black; word-wrap: normal;"><!--</code> <script src="https://jquery-csv.googlecode.com/files/jquery.csv-0.71.js"></script> </code><code style="color: black; word-wrap: normal;"><code style="color: black; word-wrap: normal;">--></code>
<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>
</code>
</pre>
<br />
<hr />
The <a href="http://economistry.com/2013/07/easy-data-visualization-with-google-charts-and-a-csv/" target="_blank">original tutorial in Economistry</a> allows one to choose both the domain (horizontal axis) and the range (vertical axis) but given <a href="http://www.quandl.com/MOSPI-Ministry-of-Statistics-India/EDU_INST_SCHOOL_EXPENDTR_29_1-EDUCATIONAL-INSTITUTIONS-SCHOOLS-AND-EXPENDITURE-INDIA" target="_blank">the nature of the data</a>, having anything other than year on the horizontal axis would make no sense.</div>
Prithwishttp://www.blogger.com/profile/14023204360522864496noreply@blogger.com0tag:blogger.com,1999:blog-6383476867437452416.post-41804599405770102272013-12-23T16:59:00.000+05:302017-06-29T16:20:04.353+05:308 Google Charts from Public CSV datasets<div dir="ltr" style="text-align: left;" trbidi="on">
<a href="http://www.quandl.com/" target="_blank">Quandl</a> 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.<br />
<br />
In this example, we see how we can access CSV data about<a href="http://www.quandl.com/MOSPI-Ministry-of-Statistics-India/EDU_INST_SCHOOL_EXPENDTR_29_1-EDUCATIONAL-INSTITUTIONS-SCHOOLS-AND-EXPENDITURE-INDIA" target="_blank"> education in India</a> from Quandl and publish it either on <a href="http://prithwis.x10.bz/charts/vzl-csv-quandl001.html" target="_blank">an HTML page</a> or in blog. This example is based on the excellent tutorial available at <a href="http://economistry.com/2013/07/easy-data-visualization-with-google-charts-and-a-csv/" target="_blank">Economistry</a> 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.<br />
<hr />
<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=MspdKdpirBQzxqZpxdov", 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="height: 500px; width: 900px;">
</div>
</body><br />
<hr />
<div style="text-align: left;">
The Javascript library <span style="background-color: #eeeeee; font-family: "andale mono" , "lucida console" , "monaco" , "fixed" , monospace; font-size: 12px; line-height: 14px;">jquery.csv-0.71.js</span> is required to convert CSV files into a format that is acceptable to the Google Data Table. You can download this from <a href="https://code.google.com/p/jquery-csv/downloads/detail?name=jquery.csv-0.71.js&can=2&q=" target="_blank">this URL</a>, 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.</div>
<hr />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono,Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code style="color: black; word-wrap: normal;">
<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> </code><code style="color: black; word-wrap: normal;">
</code><code style="color: black; word-wrap: normal;"><code style="color: black; word-wrap: normal;"><code style="color: black; word-wrap: normal;"><!--</code></code> <script src="https://jquery-csv.googlecode.com/files/jquery.csv-0.71.js"></script></code><code style="color: black; word-wrap: normal;"><code style="color: black; word-wrap: normal;">--></code><code style="color: black; word-wrap: normal;"><code style="color: black; word-wrap: normal;"><code style="color: black; word-wrap: normal;"></code></code></code>
<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>
</code>
</pre>
<hr />
In the next example, we will explore how to make these charts more interactive. Stay tuned.</div>
Prithwishttp://www.blogger.com/profile/14023204360522864496noreply@blogger.com4tag:blogger.com,1999:blog-6383476867437452416.post-41180293970464240572013-12-20T17:32:00.001+05:302013-12-31T20:07:13.403+05:307 Creating a Dashboard - Part II<div dir="ltr" style="text-align: left;" trbidi="on">
Here we take the same data used in the<a href="http://vizualyse.blogspot.in/2013/12/creating-dashboard-part-1.html" target="_blank"> previous post</a> 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 <a href="http://prithwis.x10.bz/charts/vzl-dash2-controls.html" target="_blank">regular HTML page</a>.<br />
<hr />
<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&usp=drive_web#gid=1" target="_blank">Data Source</a>
</body>
<br />
<hr />
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.
<br />
<hr />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono,Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code style="color: black; word-wrap: normal;">
<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>
</code>
</pre>
<br />
<hr />
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 !!<br />
<br />
A more sophisticated RangeFilter is shown in <a href="http://vizualyse.blogspot.in/2013/12/ril-stock-data-from-quandl-filtered-on.html" target="_blank">this post</a>. </div>
Prithwishttp://www.blogger.com/profile/14023204360522864496noreply@blogger.com0tag:blogger.com,1999:blog-6383476867437452416.post-55694996159323803082013-12-20T16:46:00.002+05:302013-12-31T20:03:52.798+05:307 Creating a Dashboard - Part 1<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
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 <a href="https://docs.google.com/a/yantrajaal.com/spreadsheet/ccc?key=0AhEX55Pfl1eedExUbS1xNzBuQVAyNDJTeG1weFQxbXc&usp=drive_web#gid=1" target="_blank">spreadsheet</a>. The chart shown below can also be seen in this <a href="http://prithwis.x10.bz/charts/vzl-dash1-colchart.html" target="_blank">regular HTML page</a>.</div>
<hr />
<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&usp=drive_web#gid=1" target="_blank">Data Source</a>
</body>
<br />
<hr />
Note how we have specified<br />
<ul style="text-align: left;">
<li>the Google Docs spreadsheet : https://docs.google.com/a/yantrajaal.com/spreadsheet/ccc?key=0AhEX55Pfl1eedExUbS1xNzBuQVAyNDJTeG1weFQxbXc</li>
<li>the sheet : sheet=MilkProduction</li>
<li>range : range=B2:H37</li>
<li>headers : headers=1</li>
<li>columns : query.setQuery('<span style="color: red;"><b>select B,E,F</b></span>');</li>
<li>chart type : var chartMQ = new google.visualization.<span style="color: red;"><b>ColumnChart</b></span>(document.getElementById('chart_divMQ'));</li>
</ul>
<hr />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono,Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code style="color: black; word-wrap: normal;">
<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 />
</code>
</pre>
<br />
<hr />
In the next post we will convert this into a Dashboard
</div>
Prithwishttp://www.blogger.com/profile/14023204360522864496noreply@blogger.com0tag:blogger.com,1999:blog-6383476867437452416.post-31715388756395916032013-12-18T13:10:00.000+05:302017-06-29T16:55:31.789+05:306 Showing Addresses on a Google Map<div dir="ltr" style="text-align: left;" trbidi="on">
In this example, we wish to show on a the locations of certain schools in Calcutta whose addresses are known. We begin with a <a href="http://www.hindustanlink.com/careertex/kolkata-schools-list-directory.htm" target="_blank">primary source of data</a> and copy the same into a Google Docs <a href="https://docs.google.com/a/yantrajaal.com/spreadsheet/ccc?key=0AhEX55Pfl1eedFpvdkxCYlgzZ0VKX2pkTmZQM2JJRlE#gid=0" target="_blank">spreadsheet</a>. This <a href="https://docs.google.com/a/yantrajaal.com/spreadsheet/ccc?key=0AhEX55Pfl1eedFpvdkxCYlgzZ0VKX2pkTmZQM2JJRlE#gid=0" target="_blank">base data</a> is then copied into a another sheet for<a href="https://docs.google.com/a/yantrajaal.com/spreadsheet/ccc?key=0AhEX55Pfl1eedFpvdkxCYlgzZ0VKX2pkTmZQM2JJRlE#gid=1" target="_blank"> pre-processing</a>. 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 <a href="https://docs.google.com/a/yantrajaal.com/spreadsheet/ccc?key=0AhEX55Pfl1eedFpvdkxCYlgzZ0VKX2pkTmZQM2JJRlE#gid=1" target="_blank">this sheet</a>.<br />
<br />
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<a href="http://ctrlq.org/code/19028-geocoding-postal-addresses" target="_blank"> Amit Agarwals Programmer's Library</a> to calculate the latitude and longitude corresponding to each school address.<br />
<br />
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 <a href="https://docs.google.com/a/yantrajaal.com/spreadsheet/ccc?key=0AhEX55Pfl1eedFpvdkxCYlgzZ0VKX2pkTmZQM2JJRlE#gid=1" target="_blank">pre-processing sheet</a>.<br />
<br />
The final, clean data consisting of the latitude, longitude and school name is now copied into the final <a href="https://docs.google.com/a/yantrajaal.com/spreadsheet/ccc?key=0AhEX55Pfl1eedFpvdkxCYlgzZ0VKX2pkTmZQM2JJRlE#gid=2" target="_blank">GeoCodeData sheet</a> for transmission to the <a href="http://prithwis.x10.bz/charts/vzl-map3-school.html" target="_blank">HTML page</a> that will display the map.<br />
<br />
From here onward, we use the templates that Google provides for <a href="https://developers.google.com/chart/interactive/docs/gallery/map" target="_blank">Map Visualisation</a> with the exception that in this case our data is not hard coded into the HTML page but is being picked up from <a href="https://docs.google.com/a/yantrajaal.com/spreadsheet/ccc?key=0AhEX55Pfl1eedFpvdkxCYlgzZ0VKX2pkTmZQM2JJRlE#gid=2" target="_blank">the spreadsheet</a>.<br />
<br />
The HTML code for this is shown in the post below. Note that we have specified the<br />
<br />
<ul style="text-align: left;">
<li>spreadsheet - through the value of the key, that can be picked up from the URL</li>
<li>sheet - in this case sheet=GeoCodeData</li>
<li>range - B2:D11</li>
<li>there are no headers</li>
<li>we use columns B,C,D where B = lat, C= long and D is a text field, in this case school name</li>
</ul>
<br />
<hr />
This is the map that is produced
<head>
<script src="https://www.google.com/jsapi" type="text/javascript"></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=0AhEX55Pfl1eedFpvdkxCYlgzZ0VKX2pkTmZQM2JJRlE&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="height: 500px; width: 600px;">
</div>
</body>
<br />
<hr />
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.<br />
<hr />
This is the GoogleScript code used in Google Docs to GeoCode addresses into lat/long positions
<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono,Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code style="color: black; word-wrap: normal;">
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);
}
}
</code>
</pre>
<hr />
This is the HTML code that is embedded in this blog
<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono,Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code style="color: black; word-wrap: normal;">
<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>
</code>
</pre>
<hr />
For some reason, the map on this blog is in black and white even though on the <a href="http://prithwis.x10.bz/charts/vzl-map3-school.html" target="_blank">normal HTML page</a> the colours are showing properly. What can be reason for this ? If anyone knows, will appreciate a suggestion.</div>
Prithwishttp://www.blogger.com/profile/14023204360522864496noreply@blogger.com0tag:blogger.com,1999:blog-6383476867437452416.post-31944870743749798882013-12-18T07:06:00.001+05:302017-06-29T16:52:41.451+05:305 State Data in Google GeoChart<div dir="ltr" style="text-align: left;" trbidi="on">
<hr />
<br />
In this map, we use data from States ( see the<a href="https://docs.google.com/a/yantrajaal.com/spreadsheet/ccc?key=0AhEX55Pfl1eedExUbS1xNzBuQVAyNDJTeG1weFQxbXc&usp=drive_web#gid=1" target="_blank"> spreadsheet</a> ) and this too can be mapped into a map of India. However state level maps are not available and the data for a particular state is mapped into a point ( or marker) in the state.<br />
<hr />
<head>
<script src="https://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load('visualization', '1', {'packages': ['geochart']});
google.setOnLoadCallback(drawMarkersMapTR);
function drawMarkersMapTR() {
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,C,D');
query.send(handleQueryResponseTR);
};
function handleQueryResponseTR(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var options = {
region: 'IN',
displayMode: 'markers',
width : 600,
height : 400
};
var data = response.getDataTable();
var chart = new google.visualization.GeoChart(document.getElementById('chart_divTR'));
chart.draw(data, options );
}
</script>
</head>
<body>
<div id="chart_divTR">
</div>
</body>
<br />
<hr />
<br />
Once again we observe the limitations of not being able to show more than two data points for each state. <br />
<hr />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono,Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code style="color: black; word-wrap: normal;">
<head>
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type='text/javascript'>
google.load('visualization', '1', {'packages': ['geochart']});
google.setOnLoadCallback(drawMarkersMapTR);
function drawMarkersMapTR() {
var query = new google.visualization.Query(
'https://docs.google.com/a/yantrajaal.com/spreadsheet/ccc?key=xxxxxxxxxxxxxx&sheet=MilkProduction&range=B2:H37&headers=1');
query.setQuery('select B,C,D');
query.send(handleQueryResponseTR);
};
function handleQueryResponseTR(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var options = {
region: 'IN',
displayMode: 'markers',
width : 600,
height : 400
};
var data = response.getDataTable();
var chart = new google.visualization.GeoChart(document.getElementById('chart_divTR'));
chart.draw(data, options );
}
</script>
</head>
<body>
<div id="chart_divTR"></div>
</body>
</code>
</pre>
<hr />
<br /></div>
Prithwishttp://www.blogger.com/profile/14023204360522864496noreply@blogger.com0tag:blogger.com,1999:blog-6383476867437452416.post-27731973299202210972013-12-17T21:05:00.003+05:302017-08-02T12:41:38.159+05:304 Plotting Cities on a Map along with Data<div dir="ltr" style="text-align: left;" trbidi="on">
In this example, we have data about certain of India -- data about number of registered vehicles in different years -- in a <a href="https://docs.google.com/a/yantrajaal.com/spreadsheet/ccc?key=0AhEX55Pfl1eedE5mUHN4QVRLNzdldEpwZnAyNy1abUE&usp=drive_web#gid=0" target="_blank">Google Docs spreadsheet</a>. We use this data to draw a Google <a href="https://google-developers.appspot.com/chart/interactive/docs/gallery/geochart" target="_blank">GeoChart</a>.<br />
<hr />
<head>
<script src="https://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load('visualization', '1', {'packages': ['geochart']});
google.setOnLoadCallback(drawMarkersMap02);
function drawMarkersMap02() {
var query = new google.visualization.Query(
'https://docs.google.com/a/yantrajaal.com/spreadsheet/ccc?key=0AhEX55Pfl1eedE5mUHN4QVRLNzdldEpwZnAyNy1abUE&sheet=CityWise2&range=B2:M23&headers=1');
query.setQuery('select B,D,E');
query.send(handleQueryResponse02);
};
function handleQueryResponse02(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var options = {
datalessRegionColor : 'FFFF99',
region: 'IN',
displayMode: 'markers',
colorAxis: {colors: ['green', 'blue']}
};
var data = response.getDataTable();
var chart = new google.visualization.GeoChart(document.getElementById('pm_div4'));
chart.draw(data, options );
}
</script>
</head>
<body>
<div id="pm_div4" style="height: 500px; width: 600px;">
</div>
</body>
<br />
<hr />
In the code please observe the following points<br />
<br />
<ol style="text-align: left;">
<li>The spreadsheet doc is identified as <span style="background-color: #eeeeee; font-family: "andale mono" , "lucida console" , "monaco" , "fixed" , monospace; font-size: 12px; line-height: 14px;">https://docs.google.com/a/yantrajaal.com/spreadsheet/ccc?key=0AhEX55Pfl1eedE5mUHN4QVRLNzdldEpwZnAyNy1abUE</span></li>
<li>The sheets as identified by <span style="background-color: #eeeeee; font-family: "andale mono" , "lucida console" , "monaco" , "fixed" , monospace; font-size: 12px; line-height: 14px;">sheet=CityWise2</span></li>
<li>The range is identified by <span style="background-color: #eeeeee; font-family: "andale mono" , "lucida console" , "monaco" , "fixed" , monospace; font-size: 12px; line-height: 14px;">range=B2:M23</span></li>
<li>The columns being selected are identified by <span style="background-color: #eeeeee; font-family: "andale mono" , "lucida console" , "monaco" , "fixed" , monospace; font-size: 12px; line-height: 14px;">query.setQuery('select B,D,E');</span></li>
<li>The region in the map is 'IN' that is India</li>
<li>The displayMode is "markers" .. which means towns and cities, had this been region we would have got full states</li>
</ol>
<br />
<hr />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono,Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code style="color: black; word-wrap: normal;">
<head>
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=myAPIkeyhere&callback=initMap"
type="text/javascript"></script>
<script type='text/javascript'>
google.load('visualization', '1', {'packages': ['geochart']});
google.setOnLoadCallback(drawMarkersMap02);
function drawMarkersMap02() {
var query = new google.visualization.Query(
'https://docs.google.com/a/yantrajaal.com/spreadsheet/ccc?key=xxxxxxxxxxxxxxx&sheet=CityWise2&range=B2:M23&headers=1');
query.setQuery('select B,D,E');
query.send(handleQueryResponse02);
};
function handleQueryResponse02(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var options = {
datalessRegionColor : 'FFFF99',
region: 'IN',
displayMode: 'markers',
colorAxis: {colors: ['green', 'blue']}
};
var data = response.getDataTable();
var chart = new google.visualization.GeoChart(document.getElementById('pm_div4'));
chart.draw(data, options );
}
</script>
</head>
<body>
<div id="pm_div4" style="width: 600px; height: 500px;"></div>
</body>
</code>
</pre>
<hr />
In creating this chart in this blog, we faced an unusual error. When viewed as an independent post, the chart was visible but when seen as a part of the blog, the chart was not drawn ?<br />
<br />
What can be the reason ? The reason was that we had the same function name in two different posts and so when two posts were visible together on the same page, the codes were interefering with each other. So we simply placed an arbitrary suffix values to the function names and it worked.<br />
<br />
The same code can be embedded in a non-blog web post<a href="http://prithwis.x10.bz/charts/vzl-map1-marker.html" target="_blank"> like this</a>.<br />
<br />
A similar map can be created <a href="https://www.simple-talk.com/dotnet/asp.net/adding-public-domain-data-to-your-software-demos-with-r/" rel="nofollow" target="_blank">using (a) public website data and (b) R statistical tool</a>.<br />
<br />
<hr />
<span style="background-color: yellow;"><span style="color: red;"><b>Google Map API</b></span></span><br />
Subsequent to the creation of these posts, Google has made it mandatory for all new domains ( or new websites, new blogs) to incorporate a Google Maps API into the HTML code :<br />
<pre style="background-color: #eeeeee; border: 1px dashed rgb(153, 153, 153); font-family: "andale mono", "lucida console", monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 653px;"><code style="word-wrap: normal;"><script async defer src="https://maps.googleapis.com/maps/api/js?key=myAPIkeyhere&callback=initMap"
type="text/javascript"></script></code></pre>
this API key can be obtained from this <a href="https://developers.google.com/maps/documentation/javascript/get-api-key" target="_blank">Google page</a>.<br />
<br /></div>
Prithwishttp://www.blogger.com/profile/11940658684717969663noreply@blogger.com1tag:blogger.com,1999:blog-6383476867437452416.post-5250987899857881352013-12-11T19:52:00.000+05:302013-12-31T20:03:01.400+05:303 Specifying Range of Data and Selecting Columns : Google Charts with Google Docs data<div dir="ltr" style="text-align: left;" trbidi="on">
In the previous post, we had described<a href="http://vizualyse.blogspot.in/2013/12/creating-google-chart-using-data-pulled.html" target="_blank"> how to create a basic Google Chart from data stored in a Google Doc spreadsheet</a>. In that example, the data was picked up from the default first sheet of the spreadsheet and the data was located in the top left corner. In reality, the data could be stored in any of the other sheets and could be located in any portion of the sheet.<br />
<br />
In this example, the Google Docs <a href="https://docs.google.com/a/yantrajaal.com/spreadsheet/ccc?key=0AqawrNPy9RHodDNvMXdPX1NqanlyLVdtbEE1dlJ3LUE&usp=drive_web#gid=3" target="_blank">spreadsheet</a>, has four sheets. For the purpose of drawing our chart we would like to specify that<br />
<br />
<ol style="text-align: left;">
<li>Data to be picked up from <b><span style="color: #cc0000;">sheet</span></b> named "Demo3"</li>
<li>Within this sheet, from the <b><span style="color: #cc0000;">range</span></b> C3:I23</li>
<li>Within this range from the <b><span style="color: #cc0000;">columns</span></b> C, D, G, H</li>
<li>Given the nature of the data we would like to<b><span style="color: #cc0000;"> multiply column G by 1000</span></b> before it is plotted</li>
</ol>
<div>
If you look at the <a href="https://docs.google.com/a/yantrajaal.com/spreadsheet/ccc?key=0AqawrNPy9RHodDNvMXdPX1NqanlyLVdtbEE1dlJ3LUE&usp=drive_web#gid=3" target="_blank">spreadsheet in a browser</a>, the URL will show up as </div>
<div>
https://docs.google.com/a/yantrajaal.com/spreadsheet/ccc?key=0AqawrNPy9RHodDNvMXdPX1NqanlyLVdtbEE1dlJ3LUE&usp=drive_web#gid=3</div>
<div>
<br /></div>
<div>
For our purpose the URL will be truncated as follows and used in the program</div>
<div>
https://docs.google.com/a/yantrajaal.com/spreadsheet/ccc?key=0AqawrNPy9RHodDNvMXdPX1NqanlyLVdtbEE1dlJ3LUE</div>
<div>
<br /></div>
<div>
This URL can also be obtained by going to the option File=>Publish to the Web</div>
<div>
<br /></div>
<div>
The chart will look as follows</div>
<hr />
<head>
<script src="https://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load("visualization", '1', {packages:['corechart']});
google.setOnLoadCallback(drawChart01);
function drawChart01() {
var query = new google.visualization.Query(
'https://docs.google.com/a/yantrajaal.com/spreadsheet/ccc?key=0AqawrNPy9RHodDNvMXdPX1NqanlyLVdtbEE1dlJ3LUE&sheet=Demo3&range=C3:I12&headers=1');
query.setQuery('select C,D,1000*G,H');
query.send(handleQueryResponse01);
}
function handleQueryResponse01(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var options = {
title: 'Industrial Production Index',
vAxis: {title: 'Sector', titleTextStyle: {color: 'red'}},
width: 800,
height : 600
};
var data = response.getDataTable();
var chart = new google.visualization.BarChart(document.getElementById('ChartSpan4'));
chart.draw(data, options );
}
</script>
<title>Sheet 2 Chart - Sheet, Range, Cols</title>
</head>
<body>
<span id="ChartSpan4"></span>
</body>
<br />
<hr />
this chart has been generated by embedding the following code in this blog. It can also be embedded in<a href="http://prithwis.x10.bz/charts/vzl-sht-rng-col.html" target="_blank"> any other HTML page</a>.
<br />
<hr />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono,Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code style="color: black; word-wrap: normal;">
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", '1', {packages:['corechart']});
google.setOnLoadCallback(drawChart01);
function drawChart01() {
var query = new google.visualization.Query(
'https://docs.google.com/a/yantrajaal.com/spreadsheet/ccc?key=0AqawrNPy9RHodDNvMXdPX1NqanlyLVdtbEE1dlJ3LUE&sheet=Demo3&range=C3:I12&headers=1');
query.setQuery('select C,D,1000*G,H');
query.send(handleQueryResponse01);
}
function handleQueryResponse01(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var options = {
title: 'Industrial Production Index',
vAxis: {title: 'Sector', titleTextStyle: {color: 'red'}},
width: 400,
height : 600
};
var data = response.getDataTable();
var chart = new google.visualization.BarChart(document.getElementById('ChartSpan4'));
chart.draw(data, options );
}
</script>
<title>Sheet 2 Chart - Sheet, Range, Cols</title>
</head>
<body>
<span id='ChartSpan4'></span>
</body>
</code>
</pre>
<br />
<hr />
<div>
<br /></div>
</div>
Prithwishttp://www.blogger.com/profile/14023204360522864496noreply@blogger.com0tag:blogger.com,1999:blog-6383476867437452416.post-10981534825351304402013-12-08T15:12:00.002+05:302013-12-31T20:02:46.709+05:302 Creating a Google Chart using data pulled from Google Docs<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
I have data lying in <a href="https://docs.google.com/spreadsheet/ccc?key=0AqawrNPy9RHodGJBQkRpX0Rrdjc2OXZMZmZmNzk3WGc&usp=sharing" target="_blank">this Google Docs spreadsheet</a>. that I want to display in this blog post or in any other html page using Google Charts.<br />
<br />
The first task is to publish this data on the web and make it visible to anyone who has the URL.<br />
<br />
Next take the following piece of code and insert it into your website.<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono,Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"><code style="color: black; word-wrap: normal;">
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", '1', {packages:['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var query = new google.visualization.Query(
'https://docs.google.com/a/yantrajaal.com/spreadsheet/ccc?key=0AqawrNPy9RHodGJBQkRpX0Rrdjc2OXZMZmZmNzk3WGc&usp=drive_web#gid=0');
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var options = {'title':'How Much PIZZA I Ate Last Night',
'width':400,
'height':600};
var chart = new google.visualization.PieChart(document.getElementById('columnchart'));
chart.draw(data, options);
}
</script>
<title>Data from a Spreadsheet</title>
</head>
<body>
<span id='columnchart'></span>
</body>
</code>
</pre>
<br />
Note the URL of the spreadsheet : https://docs.google.com/a/yantrajaal.com/spreadsheet/ccc?key=0AqawrNPy9RHodGJBQkRpX0Rrdjc2OXZMZmZmNzk3WGc&usp=drive_web#gid=0 and use this in the function drawChart()<br />
<br />
and this what you get :<br />
....................................
</div>
<head>
<script src="https://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load("visualization", '1', {packages:['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var query = new google.visualization.Query(
'https://docs.google.com/a/yantrajaal.com/spreadsheet/ccc?key=0AqawrNPy9RHodGJBQkRpX0Rrdjc2OXZMZmZmNzk3WGc&usp=drive_web#gid=0');
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var options = {'title':'How Much PIZZA I Ate Last Night',
'width':400,
'height':600};
var chart = new google.visualization.PieChart(document.getElementById('columnchart'));
chart.draw(data, options);
}
</script>
<title>Data from a Spreadsheet</title>
</head>
<body>
<span id="columnchart"></span>
</body><br />
....................<br />
the same code can be embedded in a no-blog HTML page and loaded into a webserver as <a href="http://prithwis.x10.bz/charts/bar2.html" target="_blank">seen here</a>. </div>
Prithwishttp://www.blogger.com/profile/14023204360522864496noreply@blogger.com0tag:blogger.com,1999:blog-6383476867437452416.post-77314532302483725932013-12-08T14:46:00.001+05:302013-12-08T15:20:25.546+05:30How to embed code into an HTML page<div dir="ltr" style="text-align: left;" trbidi="on">
Embedding fragments of program code into a blog post or an HTML page is always a problem because the browser finds it hard to distinguish between the actual code used to render a page and the sample code that you are trying to demo. This causes major mess ups. Here is a simple process that will make this task simpler.<br />
<br />
<div style="text-align: left;">
1. If your sample code includes HTML or you have < or > symbols in your code, then you first need to encode your sample code using any of the tools from <a href="https://www.google.co.in/search?q=free+HTML+encoder&oq=free+HTML+encoder&aqs=chrome..69i57j0.5807j0j7&sourceid=chrome&espv=210&es_sm=122&ie=UTF-8">this list</a>. However the tool that I have used to create this blog post is <a href="http://www.opinionatedgeek.com/dotnet/tools/htmlencode/encode.aspx">this HTML encoder from opinionatedgeek.com</a> . This tool will take your raw HTML as an input and generate encoded HTML. </div>
<div style="text-align: left;">
<br />2. Copy the following code into a text editor.</div>
<pre style="font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee; font-size: 12px; border: 1px dashed #999999; line-height: 14px; padding: 5px; overflow: auto; width: 100%">
<code style="color:#000000;word-wrap:normal;">
<pre style="font-family: Andale Mono,Lucida Console, Monaco, fixed, monospace; color: #000000; background-color: #eee; font-size: 12px; border: 1px dashed #999999;line-height: 14px; padding: 5px; overflow: auto; width: 100%">
<code style="color:#000000;word-wrap:normal;">
========================================
<<<<<<<YOUR encoded CODE HERE>>>>>>>
========================================
</code>
</pre>
</code>
</pre>
<div style="text-align: left;">
3. Insert your encoded sample code into the space indicated to create a block of code. Copy this code from the text editor and place it in your HTML page where you want to display the sample code. If you are using Blogger to post your code, make sure that you are in the "HTML" mode and not the "Compose" mode.</div>
<div style="text-align: left;">
<br /></div>
<div style="text-align: left;">
4. That is it. If you are in Blogger, publish your page and your are done.</div>
</div>Prithwishttp://www.blogger.com/profile/14023204360522864496noreply@blogger.com0tag:blogger.com,1999:blog-6383476867437452416.post-72188122007297783412013-12-08T13:34:00.003+05:302014-04-26T18:23:29.390+05:301 Basic Google Chart<div dir="ltr" style="text-align: left;" trbidi="on">
<br />
<!--Load the AJAX API-->
<script src="https://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['Mushrooms', 3],
['Onions', 1],
['Olives', 1],
['Zucchini', 1],
['Pepperoni', 2]
]);
// Set chart options
var options = {'title':'How Much Pizza I Ate Last Night',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div1'));
chart.draw(data, options);
}
</script>
<body>
and here i can put some text
<!--Div that will hold the pie chart-->
<div id="chart_div1">
</div>
</body>
<br />
====================================================================<br />
<pre style="background-color: #eeeeee; border: 1px dashed #999999; color: black; font-family: Andale Mono, Lucida Console, Monaco, fixed, monospace; font-size: 12px; line-height: 14px; overflow: auto; padding: 5px; width: 100%;"> <code style="color: black; word-wrap: normal;">
<!--Load the AJAX API-->
<script src="https://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['Mushrooms', 3],
['Onions', 1],
['Olives', 1],
['Zucchini', 1],
['Pepperoni', 2]
]);
// Set chart options
var options = {'title':'How Much Pizza I Ate Last Night',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div1'));
chart.draw(data, options);
}
</script>
<body>
and here i can put some text
<!--Div that will hold the pie chart-->
<div id="chart_div1">
</div>
</body>
</code>
</pre>
See the<a href="https://developers.google.com/chart/" target="_blank"> full gallery</a> of Google Charts and use<a href="https://code.google.com/apis/ajax/playground/?type=visualization" target="_blank"> this playground </a>to get the corresponding codes to copy and paste.</div>
Prithwishttp://www.blogger.com/profile/14023204360522864496noreply@blogger.com0tag:blogger.com,1999:blog-6383476867437452416.post-32965409880743534422013-12-08T13:27:00.003+05:302013-12-08T13:27:55.919+05:30Vizualyse<div dir="ltr" style="text-align: left;" trbidi="on">
A place to collect and explore visualizations.</div>
Prithwishttp://www.blogger.com/profile/14023204360522864496noreply@blogger.com0