我想生成一个图形,有一个基本图形和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)")

这就产生了

这些小组中的大多数看起来足以让我将其纳入我的报告中.然而,显示自相关性的曲线图需要改进.通过使用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()

在此处输入图像描述

然而,作为GGTRAP不是基础图形,我们不能结合GGPrice与布局或PAR(MFROW).如何用ggplot生成的自相关图替换从基本图形生成的自相关图?我知道我可以使用网格.如果我所有的图形都是用ggplot绘制的,那我该怎么做呢?如果ggplot中只生成了一个图形呢?

推荐答案

使用gridBase包,只需添加两行即可.我想如果你想用网格做有趣的情节,你只需要理解并掌握viewports.它实际上是网格包的基本对象.

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

函数的作用是:返回三个栅格视口的列表.我在这里使用图形视口

以下是最终解决方案:

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

R相关问答推荐

从载体创建 pyramid

使用Shiny组合和显示复制和粘贴的数据

使用gggplot 2在R中重新调整面板和y轴文本大小

多个ggpredicate对象的平均值

创建重复删除的唯一数据集组合列表

以R为基数排列奇数个图

如何使用stat_extract_all正确提取我的目标值?

如何计算前一行的值,直到达到标准?

用预测NLS处理R中生物学假设之上的误差传播

R函数‘paste`正在颠倒其参数的顺序

我如何才能找到FAMILY=POISSON(LINK=&Q;LOG&Q;)中的模型预测指定值的日期?

提取一个列表中单个列的重复观察结果R

如何在PackageStatus()中列出&q;不可用的包&q;?

汇总数据的Sheffe检验的P值(平均值和标准差)

R如何将列名转换为更好的年和月格式

R中时间间隔的大向量与参考时间间隔的相交

计算来自单独分组的分幅的值的百分位数

有没有办法将勾选/审查标记添加到R中的累积关联图中?

随机生成样本,同时在R内的随机样本中至少包含一次所有值

修复标签重叠和ggploy内的空间