Skip to content

Instantly share code, notes, and snippets.

@xccds
Created May 3, 2012 13:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xccds/2585753 to your computer and use it in GitHub Desktop.
Save xccds/2585753 to your computer and use it in GitHub Desktop.
# 加载所需扩展包
library(RCurl)
library(RJSONIO)
require(quantmod)
library(ggplot2)
# 提取武汉市2011年一年的历史数据
date <- seq.Date(from=as.Date('2011-01-01'),
to=as.Date('2011-12-31'), by='1 day')
date.range <- as.character(format(date,"%Y%m%d"))
n <- length(date.range)
temp <- humi <- rep(0,n)
for (i in 1:n) {
# 你要用自己申请的API key来代替程序中的yourkey
url <- 'http://api.wunderground.com/api/yourkey/'
finalurl <- paste(url,'history_',date.range[i],
'/q/wuhan.json',sep='')
web <- getURL(finalurl)
raw <-fromJSON(web)
temp[i] <- raw$history$dailysummary[[1]]$meantempm
humi[i] <- raw$history$dailysummary[[1]]$humidity
# 在循环内增加一个7秒的暂停,避免连接断开。
Sys.sleep(7)
}
# 将获得的数据整合为数据框,并将温度和湿度转为数值格式
dataset <- data.frame(temp,humi,date,stringsAsFactors=F)
dataset$temp <- as.numeric(dataset$temp)
dataset$humi <- as.numeric(dataset$humi)
# 用openair包绘制日历热图
install.packages('openair')
library(openair)
calendarPlot(dataset,pollutant='temp',year=2011)
# 用ggplot2包绘制日历热图
# 复制一个新的数据框
dat <- dataset
# 先取得月份,再转为因子格式
dat$month<-as.numeric(as.POSIXlt(dat$date)$mon+1)
dat$monthf<-factor(dat$month,levels=as.character(1:12),
labels=c("Jan","Feb","Mar","Apr","May","Jun","Jul",
"Aug","Sep","Oct","Nov","Dec"),ordered=TRUE)
# 得到每周的星期,也转为因子格式
dat$weekday = as.POSIXlt(dat$date)$wday
dat$weekdayf<-factor(dat$weekday,levels=rev(0:6),
labels=rev(c("Sun","Mon","Tue","Wed","Thu","Fri","Sat")),ordered=TRUE)
# 先得到全年的周序号,然后得到每个月的周序号
dat$week <- as.numeric(format(dat$date,"%W"))
dat<-ddply(dat,.(monthf),transform,monthweek=1+week-min(week))
# 绘图
P <- ggplot(dat, aes(monthweek, weekdayf, fill = temp)) +
geom_tile(colour='white') +
facet_wrap(~monthf ,nrow=3) +
scale_fill_gradient(space="Lab",limits=c(22, max(dat$value)),
low="red", high="yellow") +
opts(title = "武汉市2011年气温日历热图") +
xlab("Week of Month") + ylab("")
P
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment