我試圖複製ggplot2書籍的第86頁上的Hadley Wickham的示例,其中他覆蓋了geom_rects,失業趨勢。這裏是我的核心代碼,一些樣本數據:geom_rect failure:eval(expr,envir,enclos)中的錯誤:找不到對象'變量'
library("ggplot2")
library("reshape2")
library("lubridate")
con <- textConnection("Date,Var1,Var2
8-Jan-12,100.8,116
15-Jan-12,99.4,115.5
22-Jan-12,98.4,115
28-Jan-12,97.1,114
4-Feb-12,95.9,112
11-Feb-12,95.3,113
18-Feb-12,93.9,111.5
25-Feb-12,93.5,111.5
3-Mar-12,92.6,110
10-Mar-12,91.4,108
17-Mar-12,90.2,106.8
24-Mar-12,90,107.5
31-Mar-12,89.9,106
5-Apr-12,90.4,106.5
12-Apr-12,89.8,106")
track <- read.csv(con, header=TRUE)
track$Date <- as.Date(dmy(track$Date))
track <- melt(track,
id.vars = c("Date"))
con <- textConnection("City,From,To
Auckland,5-Apr-12,10-Apr-12
Brussels,1-Apr-12,3-Apr-12
Cleveland,24-Jan-12,26-Jan-12
Darjeeling,18-Jan-12,19-Jan-12
Erehwon,8-Feb-12,10-Feb-12
Florence,5-Mar-12,7-Mar-12
Gandalf,25-Mar-12,27-Mar-12")
trips <- read.csv(con, header=TRUE)
trips$From <- as.Date(dmy(trips$From))
trips$To <- as.Date(dmy(trips$To))
# draw the Time Series data
p <- ggplot(track,
aes(x = Date,
y = value,
colour=variable,
group = variable))
p <- p + geom_smooth()
p <- p + geom_point(size=3)
p <- p + geom_vline(data=trips,
aes(xintercept=From),
colour='steelblue') # departure dates
p <- p + geom_vline(data=trips,
aes(xintercept=To),
colour='grey80') # return dates
yrng <- c(80,120)
p <- p + scale_y_continuous(limits=yrng)
p # this works up to here, using vlines (ugly, but makes the point)
# ----------- THIS geom_rect() STOPS THIS PLOT BEING RENDERED
p2 <- p + geom_rect(aes(NULL, NULL, xmin=From, xmax=To),
ymin=yrng[1], ymax=yrng[2],
data=trips)
p2 # this gives an error message
# Error in eval(expr, envir, enclos) : object 'variable' not found
# ----------- THIS NOW WORKS, THANKS TO @smu, SEE BELOW
p2 <- p + geom_rect(aes(NULL, NULL, xmin=From, xmax=To,
colour=NULL, group=NULL),
ymin=yrng[1], ymax=yrng[2],
fill='orange',
alpha=0.4,
data=trips)
p2 # and I have added fill and alpha to prettify it a bit
至於建議由@泰勒 - 林克,我已編輯的代碼包含原始錯誤及解決方案通過@smu指出。謝謝。
@gauden您可以發佈的修補程序作爲一個編輯來設置你的原始文章的完整性? – 2012-04-14 15:07:38