User Tools

Site Tools


r:googlevis

Worldbank data e.g.

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

## 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

Google Gauge Chart

library(googleVis)
CityPopularity
ex1 <-gvisGauge(CityPopularity, options=list(min=0, max=800, 
                 greenFrom=500, greenTo=800, 
                 yellowFrom=300, yellowTo=500,
                 redFrom=0, redTo=300, width=400, height=300))
plot(ex1)

Pie charts

library(googleVis)
CityPopularity
pie1 <- gvisPieChart(CityPopularity,options=list(width=400, height=300)) 
plot(pie1)

Bar charts

library(googleVis)
fruits=data.frame(month=c("JAN","FEB","MAR"),
                  apple=c(30,10,20),
                   orange=c(20,40,30))
line <- gvisLineChart(fruits)
plot(line)

# 양쪽면에 y축 표시하기
line2 <- gvisLineChart(fruits,"month",c("apple","orange"),
         option=list(series="[{targetAxisIndex:0},
                             {targetAxisIndex:1}]",
         vAxes="[{title:'apple'},{title:'orange'}]" ))

plot(line2)

# 선모양 변경하기
line3 <- gvisLineChart(fruits,xvar="month",yvar=c("apple","orange"),
         options=list(series="[{color:'blue',targetAxisIndex:0,
                                linewidth:1,lineDashStyle:[1,10,1,10,1,10]},
                               {color:'red',targetAxisIndex:1,
                                linewidth:2,lineDashStyle:[4,1]}]",
                      vAxes="[{title:'apple'},{title:'orange'}]" ))
plot(line3)

gbar <- gvisBarChart(fruits)
plot(gbar)

Bubble charts

library(googleVis)
Fruits
a <- gvisBubbleChart(Fruits, idvar="Fruit", xvar="Sales", yvar="Expenses", 
                     colorvar="Year", sizevar="Profit", 
                     options=list(height=500,weight=800,
                                  hAxis='{minValue:75, maxValue:125}'))
plot(a)

Public Parking Places

setwd("D:/Users/Hyo/Cs-Kant/CS/Rdata/rloveyou")
install.packages("ggmap")
install.packages("stringr")
library(ggmap)
library(stringr)

loc <- read.csv("서울_강동구_공영주차장_위경도.csv")
loc
kd <- get_map("Amsa-dong",zoom=13, maptype = "roadmap")

kor.map <- ggmap(kd)+geom_point(data=loc, aes(x=LON, y=LAT),
            size=3,alpha=0.7,color="red")
kor.map + geom_text(data=loc, aes(x = LON, y = LAT+0.001, label=주차장명),size=3)
ggsave("kd.png",dpi=500)

# 시립 구립 구분하기
loc2 <- str_sub(loc$주차장명,start=-2,end=-2)
loc2
colors <- c()
for ( i in 1:length(loc2)) {
  if (loc2[i] == '구' ) {
     colors <- c(colors,"red") }
  else { 
    colors <- c(colors,"blue") }
 }

kd <- get_map("Amsa-dong",zoom=13, maptype = "roadmap")
kor.map <- ggmap(kd)+geom_point(data=loc, aes(x=LON, y=LAT),
             size=3,alpha=0.7,color=colors)
kor.map + geom_text(data=loc, aes(x = LON, y = LAT+0.001, label=주차장명),size=3)
 
ggsave("kd2.png",dpi=500)

Places in Jeju

install.packages("googleVis")
install.packages("ggmap")

Sys.setlocale("LC_CTYPE", "en_US.UTF-8")
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("제주여행코스.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)

Population by districts

library(ggmap)
library(grid)
pop <- read.csv("지역별인구현황_2014_4월기준.csv",header=T)
pop
lon <- pop$LON
lat <- pop$LAT
data <- pop$총인구수
df <- data.frame(lon,lat,data)
df
map1 <- get_map("Jeonju",zoom=7 , maptype='roadmap')
map1 <- ggmap(map1)
map1 + geom_point(aes(x=lon,y=lat,colour=data,size=data),data=df)
ggsave("pop.png",scale=1,width=7,height=4,dpi=500)
r/googlevis.txt · Last modified: 2017/06/07 17:23 by hkimscil

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki