plot - Combine base and ggplot graphics in R figure window -
i generate figure has combination of base , ggplot graphics. following code shows figure using base plotting functions of r:
t <- c(1:(24*14)) p <- 24 <- 10 y <- a*sin(2*pi*t/p)+20 par(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)")
which generates
most of these panels sufficient me include in report. however, plot showing autocorrelation needs improved. looks better using 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()
however, seeing ggplot not base graphic, cannot combine ggplot layout or par(mfrow). how replace autocorrelation plot generated base graphics 1 generated ggplot? know can use grid.arrange if of figures made ggplot how do if 1 of plots generated in ggplot?
using gridbase package, can adding 2 lines. think if want funny plot grid need understand , master viewports. basic object of grid package.
vps <- baseviewports() pushviewport(vps$figure) ## in space of autocorrelation plot
the baseviewports() function returns list of 3 grid viewports. use here figure viewport viewport corresponding figure region of current plot.
here how looks final solution:
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") ## last 1 current plot plot.new() ## suggested @josh vps <- baseviewports() pushviewport(vps$figure) ## in space of autocorrelation plot vp1 <-plotviewport(c(1.8,1,0,1)) ## create new vp margins, play 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")+ ## setting in title near other plots theme(plot.title = element_text(size = rel(1.4),face ='bold')) print(p,vp = vp1) ## suggested @bpatiste
Comments
Post a Comment