在R圖窗口中組合基礎和ggplot圖形我想生成一個具有base和ggplot圖形組合的圖形。以下代碼使用R的基本繪圖函數顯示我的圖:t <- c(1:(24*14)) P <- 24 A <- 10 y <- A*sin(2*pi*t/P)+20par(mfrow=c(2,2))plot(y,type = "l",xlab = "Time (hours)",ylab = "Amplitude",main = "Time series")acf(y,main = "Autocorrelation",xlab = "Lag (hours)", ylab = "ACF")spectrum(y,method = "ar",main = "Spectral density function",
xlab = "Frequency (cycles per hour)",ylab = "Spectrum")require(biwavelet)t1 <- cbind(t, y)wt.t1=wt(t1)plot(wt.t1, plot.cb=FALSE, plot.phase=FALSE,main = "Continuous wavelet transform",
ylab = "Period (hours)",xlab = "Time (hours)")哪個生成 這些面板中的大多數看起來足以讓我包含在我的報告中。但是,需要改進顯示自相關的圖。使用ggplot看起來好多了:require(ggplot2)acz <- acf(y, plot=F)acd <- data.frame(lag=acz$lag, acf=acz$acf)ggplot(acd, aes(lag, acf)) + geom_area(fill="grey") +
geom_hline(yintercept=c(0.05, -0.05), linetype="dashed") +
theme_bw()但是,由于ggplot不是基本圖形,我們無法將ggplot與布局或par(mfrow)結合起來。我怎樣才能用ggplot生成的自相關圖替換基本圖形生成的自相關圖?我知道如果我的所有數據都是用ggplot制作的話我可以使用grid.arrange但是如果只有一個圖是在ggplot中生成的話我該怎么辦呢?
3 回答

不負相思意
TA貢獻1777條經驗 獲得超10個贊
您可以將print命令與grob和viewport一起使用。
首先繪制基礎圖形,然后添加ggplot
library(grid)# Let's say that P is your plotP <- ggplot(acd, # etc... )# create an apporpriate viewport. Modify the dimensions and coordinates as neededvp.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 commandprint(P, vp=vp.BottomRight)

慕標琳琳
TA貢獻1830條經驗 獲得超9個贊
我是gridGraphics包的粉絲。出于某種原因,我遇到了gridBase的問題。
library(ggplot2)library(gridGraphics)data.frame(x = 2:10, y = 12:20) -> datplot(dat$x, dat$y)grid.echo()grid.grab() -> mapgrobggplot(data = dat) + geom_point(aes(x = x, y = y)) pushViewport(viewport(x = .8, y = .4, height = .2, width = .2)) grid.draw(mapgrob)
- 3 回答
- 0 關注
- 712 瀏覽
添加回答
舉報
0/150
提交
取消