User Tools

Site Tools


r:googlevis

This is an old revision of the document!


Worldbank data e.g.

install.packages("googleVis")
library(googleVis)
demo(WorldBank)
## Sys.setlocale("LC_CTYPE", "en_US.UTF-8")  ## comment out if encoding problem occurs

## SOURCE: http://lamages.blogspot.co.uk/2011/09/accessing-and-plotting-world-bank-data.html

## This demo shows how country level data can be accessed from the World Bank via their API and displayed with a Motion Chart.
## Inspired by Google's Public Data Explorer, see 
# http://www.google.com/publicdata/home
## 
## For the World Bank Data terms of use see:
## http://data.worldbank.org/summary-terms-of-use
##
## To run this demo an internet connection and Flash are required.
## This demo is part of the googleVis R package.
##
## Markus Gesmann, 24 September 2011  (THANK YOU TO ALL AUTHORS & CREATORS!)

## Ryan > I updated the 12000 per.page to 14000 because the data was 'clipping' - missing some

install.packages("googleVis")

library(googleVis)

getWorldBankData <- function(id='SP.POP.TOTL', date='1960:2010',
                             value="value", per.page=14000){ 
  require(RJSONIO)
  url <- paste("http://api.worldbank.org/countries/all/indicators/", id,
               "?date=", date, "&format=json&per_page=", per.page,
               sep="")
  wbData <- fromJSON(url)[[2]]
  wbData = data.frame(
    year = as.numeric(sapply(wbData, "[[", "date")), 
    value = as.numeric(sapply(wbData, function(x)
      ifelse(is.null(x[["value"]]),NA, x[["value"]]))),  
    country.name = sapply(wbData, function(x) x[["country"]]['value']),
    country.id = sapply(wbData, function(x) x[["country"]]['id'])    
  )
  
  names(wbData)[2] <- value
  return(wbData)
}

## OK - that above is the function that calls DATA (JSON format) from the 
## world bank APIs that have been exposed to make info available - 
## when called, you'll see the variables populate

getWorldBankCountries <- function(){
  require(RJSONIO)
  wbCountries <-
    fromJSON("http://api.worldbank.org/countries?per_page=14000&format=json") 
  wbCountries <- data.frame(t(sapply(wbCountries[[2]], unlist)))
  wbCountries$longitude <- as.numeric(wbCountries$longitude)
  wbCountries$latitude <- as.numeric(wbCountries$latitude)
  levels(wbCountries$region.value) <- gsub(" \\(all income levels\\)",
                                           "", levels(wbCountries$region.value))
  return(wbCountries)
}
### now pull the countries and the locations

## Create a string 1960:this year, e.g. 1960:2011
years <- paste("1960:", format(Sys.Date(), "%Y"), sep="")
## this just makes a string that says "1960:2014" - that's it

## Fertility rate
fertility.rate <- getWorldBankData(id='SP.DYN.TFRT.IN',
                                   date=years, value="fertility.rate")
## calls the function iwth instructions to pull fertility data

## Life Expectancy
life.exp <- getWorldBankData(id='SP.DYN.LE00.IN',  date=years,
                             value="life.expectancy") 
##calls function to get hte life expectancy (same function, different id to API)


## Population
population <- getWorldBankData(id='SP.POP.TOTL',  date=years,
                               value="population")
### and population - again, same funciton, different ID, different query, different data returns (12k-15k obs)


## GDP per capita (current US$)
GDP.per.capita <- getWorldBankData(id='NY.GDP.PCAP.CD',
                                   date=years,
                                   value="GDP.per.capita.Current.USD") 
## and one more trip to the API to get the GDP data

## Merge data sets
wbData <- merge(life.exp, fertility.rate)
wbData <- merge(wbData, population)
wbData <- merge(wbData, GDP.per.capita)
## RA > I'm not sure if merge requres the left hand column to be same across all sets 
## like a KEY - and if needs to be in same order, but suggest checking/testing/researching
## if you are hacking your own data in here
head(wbData)
dim(wbData)

## Get country mappings
wbCountries <- getWorldBankCountries()
head(wbCountries)
## returns a BEAUTIFUL key:
## header id  iso2Code    name    region.id    region.value    adminregion.id    adminregion.value    incomeLevel.id    incomeLevel.value    lendingType.id    lendingType.value    capitalCity    longitude    latitude
## 1st row 1    ABW    AW    Aruba    LCN    Latin America & Caribbean              NOC    High income: nonOECD    LNX    Not classified    Oranjestad    46    57

## Add regional information
wbData <- merge(wbData, wbCountries[c("iso2Code", "region.value", 
                                      "incomeLevel.value")],
                by.x="country.id", by.y="iso2Code")
## here is magic of merge

## Filter out the aggregates and country id column
subData <- subset(wbData, !region.value %in% "Aggregates" , select=
                    -country.id) 
## SUBDATA is only 9.9k long, rather than 12k (filtered Aggregates) // 12k may not be enougn anymore

## Create a motion chart!!!!!!!!!!!!!! (make sure you save first!)
M <- gvisMotionChart(subData, idvar="country.name", timevar="year",
                     options=list(width=700, height=600))
## using SubData that looks like this:
# id  iso2Code    name    region.id    region.value    adminregion.id    adminregion.value    incomeLevel.id    incomeLevel.value    lendingType.id    lendingType.value    capitalCity    longitude    latitude
# 1    ABW    AW    Aruba    LCN    Latin America & Caribbean              NOC    High income: nonOECD    LNX    Not classified    Oranjestad    46    57
# 2    AFG    AF    Afghanistan    SAS    South Asia    SAS    South Asia    LIC    Low income    IDX    IDA    Kabul    193    120
# 3    AFR    A9    Africa    NA    Aggregates              NA    Aggregates         Aggregates         1    1

## Wont "do" anything except prepare the data in "M" for the plot

## Display the chart in your browser
plot(M)

## awesome!

## SOURCE: http://lamages.blogspot.co.uk/2011/09/accessing-and-plotting-world-bank-data.html
## ORIGiNAL SOURCE: Posted by Markus Gesmann 
## comments and a few tweaks by Ryan Anderson www.dreamtolearn.com 

subway line 5-8 boarding-unboarding passenger

setwd("D:/Users/Hyo/Cs-Kant/CS/Rdata/rloveyou")

library(googleVis)
sub58 <- read.csv("서울지하철_5-8호선_이용현황_시간대별.csv",header=T)
sub58
sub58_2 <- gvisMotionChart(sub58,idvar="호선명",timevar="시간")
plot(sub58_2)

Hurricane Andrew

setwd("D:/Users/Hyo/Cs-Kant/CS/Rdata/rloveyou")

library(googleVis)
data(Andrew)
Andrew
storm1 <- gvisMap(Andrew, "LatLong" , "Tip",
               options=list(showTip=TRUE, showLine=TRUE, enableScrollWheel=TRUE,
                            mapType='hybrid', useMapTypeControl=TRUE,
                            width=800,height=400))
plot(storm1)

Seoul District Office marking

Places in Jeju

install.packages("ggmap")
library(googleVis)
library(ggmap)
 
ft_placelst <- function(place) {
   temp <- geocode(place) # 이부분이 핵심!! 위도 경도를 임시변수에 담습니다
   place <- gsub("제주 ","",place)
   df_lst <- cbind(place,temp) # 여행지이름 위도 경도'로 이루어진 데이터프레임
   
   return(df_lst)
}
 
df_placelst <- ft_placelst(readLines("jeju_places.txt"))
latlong <- paste(df_placelst$lat,":",df_placelst$lon)
latlong <- gsub(" ","",latlong)
 
df_placelst <- cbind(df_placelst, latlong)
df_placelst
placePath <- gvisMap(df_placelst, "latlong" ,"place" , 
                     options=list(showTip=TRUE, showLine=TRUE, 
                                  enableScrollWheel=TRUE, 
                                  mapType='hybrid', 
                                  useMapTypeControl=TRUE, 
                                  width=800,height=1000))
plot(placePath)
r/googlevis.1496795107.txt.gz · Last modified: 2017/06/07 08:55 by hkimscil

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki