在 R 图形窗口中组合基础图形和 ggplot 图形

我想生成一个具有基础图形和 ggplot 图形组合的图形。下面的代码使用 R 的基本绘图函数显示了我的图形:

t <- c(1:(24*14))
P <- 24
A <- 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)")

这就产生了 enter image description here

这些小组中的大多数看起来足够我在我的报告中包括。然而,显示自相关性的图需要改进。通过使用 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()

enter image description here

但是,由于 ggplot 不是基础图形,因此不能将 ggplot 与布局或 par (mfrow)组合。如何用 ggplot 生成的相关图代替基础图形生成的图形?我知道如果我的所有图形都是用 ggplot 生成的,那么我可以使用 grid. install,但是如果只有一个图形是用 ggplot 生成的,那么我如何做到这一点呢?

26287 次浏览

使用 gridBase 包,只需添加2行即可完成。我认为如果你想做有趣的情节与网格你只需要了解和掌握 视窗。它实际上是网格包的基本对象。

vps <- baseViewports()
pushViewport(vps$figure) ##   I am in the space of the autocorrelation plot

BaseViewports ()函数返回三个网格视口的列表 对应于 目前图形区域的视图。

以下是最终解决方案的样子:

enter image description here

library(gridBase)
library(grid)


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

可以将 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)

我是 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)

enter image description here

cowplot 程序包具有 recordPlot()功能,可以捕获基本 R 图,从而将它们组合在一起形成 plot_grid()功能。

library(biwavelet)
library(ggplot2)
library(cowplot)
library(gridGraphics)


t <- c(1:(24*14))
P <- 24
A <- 10
y <- A*sin(2*pi*t/P)+20


plot(y,type = "l",xlab = "Time (hours)",ylab = "Amplitude",main = "Time series")
### record the previous plot
p1 <- recordPlot()


spectrum(y,method = "ar",main = "Spectral density function",
xlab = "Frequency (cycles per hour)",ylab = "Spectrum")
p2 <- recordPlot()


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)")
p3 <- recordPlot()


acz <- acf(y, plot=F)
acd <- data.frame(lag=acz$lag, acf=acz$acf)
p4 <- ggplot(acd, aes(lag, acf)) + geom_area(fill="grey") +
geom_hline(yintercept=c(0.05, -0.05), linetype="dashed") +
theme_bw()


### combine all plots together
plot_grid(p1, p4, p2, p3,
labels = 'AUTO',
hjust = 0, vjust = 1)

Reprex 软件包于2019-03-17创作(0.2.1.9000)

另一种选择是使用带有 作者: As.ggplot函数的 Ggplotify包,该函数将基本 R 图转换为 ggplot对象。然后,您可以使用 patchwork布局结构将该图与实际的 ggplot结合起来。下面是一个可重复的例子:

set.seed(1) # Reproducible
df <- data.frame(x = runif(10,0,1),
y = runif(10,0,1))
library(ggplot2)
library(ggplotify)
library(patchwork)
# ggplot
p_ggplot <- ggplot(df, aes(x = x, y = y)) +
geom_point()


# Combine base graph and ggplot
as.ggplot(~plot(df$x, df$y)) + p_ggplot

创建于2022-08-22与 Reprex v2.0.2

正如您可以看到的,基本图和 ggplot 图组合在一个图形窗口中。

可以将更多不同类型的图形对象组合在一起,如文档中所述:

将 plot 函数调用(使用表达式或公式)转换为“ grob”或 与“ grid”和“ ggplot2”生态系统兼容的“ ggplot”对象。 有了这个软件包,我们就能够使用“牛图”来对齐情节 由「基本」图形、「网格」、「格子」、「 vcd 」等制作 将它们转换为“ ggplot”对象。