我是gridGraphics包的粉丝。出于某种原因,我遇到了gridBase的问题。
library(ggplot2) library(gridGraphics) data.frame(x = 2:10, y = 12:20) -> dat plot(dat$x, dat$y) grid.echo() grid.grab() -> mapgrob ggplot(data = dat) + geom_point(aes(x = x, y = y)) pushViewport(viewport(x = .8, y = .4, height = .2, width = .2)) grid.draw(mapgrob)
您可以将print命令与grob和viewport一起使用。 首先绘制基础图形,然后添加ggplot
library(grid) # Let's say that P is your plot P <- ggplot(acd, # etc... ) # create an apporpriate viewport. Modify the dimensions and coordinates as needed vp.BottomRight <- viewport(height=unit(.5, "npc"), width=unit(0.5, "npc"), just=c("left","top"), y=0.5, x=0.5) # plot your base graphics par(mfrow=c(2,2)) plot(y,type #etc .... ) # plot the ggplot using the print command print(P, vp=vp.BottomRight)
使用gridBase包,只需添加2行即可。我想如果你想用网格做有趣的情节你需要理解和掌握 的 视 强> 。它实际上是网格包的基本对象。
vps <- baseViewports() pushViewport(vps$figure) ## I am in the space of the autocorrelation plot
baseViewports()函数返回三个网格视口的列表。我在这里用图视口 对应于图形区域的视口 的 当前 强> 情节。
它是如何看待最终的解决方案:
library(gridBase) par(mfrow=c(2, 2)) plot(y,type = "l",xlab = "Time (hours)",ylab = "Amplitude",main = "Time series") plot(wt.t1, plot.cb=FALSE, plot.phase=FALSE,main = "Continuous wavelet transform", ylab = "Period (hours)",xlab = "Time (hours)") spectrum(y,method = "ar",main = "Spectral density function", xlab = "Frequency (cycles per hour)",ylab = "Spectrum") ## the last one is the current plot plot.new() ## suggested by @Josh vps <- baseViewports() pushViewport(vps$figure) ## I am in the space of the autocorrelation plot vp1 <-plotViewport(c(1.8,1,0,1)) ## create new vp with margins, you play with this values require(ggplot2) acz <- acf(y, plot=F) acd <- data.frame(lag=acz$lag, acf=acz$acf) p <- ggplot(acd, aes(lag, acf)) + geom_area(fill="grey") + geom_hline(yintercept=c(0.05, -0.05), linetype="dashed") + theme_bw()+labs(title= "Autocorrelation\n")+ ## some setting in the title to get something near to the other plots theme(plot.title = element_text(size = rel(1.4),face ='bold')) print(p,vp = vp1) ## suggested by @bpatiste