【问题标题】:Combine base and ggplot graphics in R figure window在 R 图形窗口中组合 base 和 ggplot 图形
【发布时间】:2012-12-16 22:58:30
【问题描述】:

我想生成一个结合了基本图形和 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()

但是,由于 ggplot 不是基本图形,我们不能将 ggplot 与 layout 或 par(mfrow) 结合起来。如何用 ggplot 生成的自相关图替换从基础图形生成的自相关图?我知道如果我的所有图形都是用 ggplot 制作的,我可以使用 grid.arrange 但是如果在 ggplot 中只生成一个图,我该怎么做?

【问题讨论】:

  • 使用polygonacf() 的输出来构建类似于ggplot 的基本图形图可能几乎一样简单,而且看起来更一致。
  • 感谢我们的回复。这个问题的真正目的是学习如何在图形窗口中组合 ggplot 和基本图形,我意识到可能有更有效的方法来生成显示的图形,但为了将来的目的,我想学习指定的方法。
  • 查看gridBase 包...
  • 您可能想看看gridGraphics 包,它“[重绘]基本图形为网格图形”。
  • 虽然它被标记为重复,但这个答案对我来说非常有效:stackoverflow.com/a/21857177/1436851

标签: r plot ggplot2 base biwavelet


【解决方案1】:

使用 gridBase 包,只需添加 2 行即可。我认为如果你想用网格做有趣的情节,你只需要理解和掌握 viewports。确实是grid包的基础对象。

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

baseViewports() 函数返回三个网格视口的列表。我在这里使用图视口 当前绘图的图形区域对应的视口。

这是最终解决方案的样子:

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

【讨论】:

  • 是的,我已经尝试过了,问题是 ggplot 生成的图比其他面板大得多(如上所示)。有没有办法改变这个?
  • +1 非常好。如果您将调用acf(...) 替换为调用plot.new(),您将避免调用grid.rect() 来“白化”acf 图。
  • 刚刚 b/c 我回来了,看到你添加了这个更简单、更聪明的答案。
  • @JoshO'Brien 非常感谢!
  • 而不是 grid.draw(ggplotGrob(p)) 我会在 ggplot 对象的 print 方法中使用 vp 参数。
【解决方案2】:

您可以将打印命令与 grob 和视口一起使用。
首先绘制你的基础图形,然后添加 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)

【讨论】:

  • 你好,里卡多。你知道如何用你的方法控制绘图的宽度吗?例如,我想要一个基本图形和一个 ggplot2 图形并排,但基本图形的宽度更大。
  • 嗨 Stéphane,您可以通过调整viewport() 行中的设置来完成此操作。具体来说,您需要调整 widthy 值,尝试不同的值,直到获得所需的结果。
  • 谢谢里卡多。其实我在这里有一个问题stackoverflow.com/questions/14358526/…
【解决方案3】:

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

【讨论】:

    【解决方案4】:

    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 package (v0.2.1.9000) 于 2019 年 3 月 17 日创建

    【讨论】:

      猜你喜欢
      • 2015-08-24
      • 2013-06-02
      • 1970-01-01
      • 2017-05-21
      • 1970-01-01
      • 2015-12-17
      相关资源
      最近更新 更多