首页 文章

在组合ggplot和基本图形时,使面板具有相同的边距

提问于
浏览
10

我已经生成了一个结合了ggplot和基本图形的图形:

t <- c(1:(24*14)) 
P <- 24
A <- 10 
y <- A*sin(2*pi*t/P)+20 
#*****************************************************************************
par(mfrow = c(2,1))
plot(y,type = "l",xlab = "Time (hours)",ylab = "Amplitude")
aa <- par("mai")
plot.new()

require(gridBase)
vps <- baseViewports()
pushViewport(vps$figure)
pushViewport(plotViewport(margins = aa)) ## I use 'aa' to set the margins 
#*******************************************************************************
require(ggplot2)
acz <- acf(y, plot = FALSE)
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()
grid.draw(ggplotGrob(p)) ## draw the figure

我使用plotViewport命令并根据第一个面板的尺寸设置面板的尺寸,通过par("mai")获得 . 附图显示了结果 .
enter image description here
但是,两个面板的尺寸不匹配,即第二个面板似乎比第一个面板略宽 . 如何在不必手动设置边距的情况下克服此问题

pushViewport(plotViewport(c(4,1.2,0,1.2)))

2 回答

  • 3

    这应该给你一些提示:

    screenshot

    library(grid)
    library(ggplot2)
    require(gridBase)
    
    par(mfrow = c(2,1))
    plot(1:10)
    a <- par("mai")
    plot.new()
    vps <- baseViewports()
    pushViewport(vps$figure)
    
    p = qplot(1:10, 1:10) + theme_bw() 
    g <- ggplotGrob(p)
    
    lw = unit(a[2], "inch") - sum(g$widths[1:3]) 
    
    g$widths[[2]] <- as.list(lw + g$widths[[2]])
    g$widths[[4]] <- as.list(unit(1, "npc") - unit(a[2] + a[4], "inch"))
    g$widths[[5]] <- unit(a[4], "inch")
    grid.draw(g)
    
    # draw a shaded vertical band to test the alignment
    grid.rect(unit(a[2], "inch"), unit(0, "inch"), 
              unit(1,"npc") - unit(a[2] + a[4], "inch"), 
              unit(2,"npc"),
              gp=gpar(lty=2, fill="red", alpha=0.1), hjust=0, vjust=0)
    
    upViewport()
    

    但是,真的,你为什么不在ggplot2中做所有事情?

  • 6

    主要思想是推动2个视口的baseviewports以获得绘图面板的尺寸 . 解决方案不是一般的 .

    首先,我绘制我的基本情节

    t <- c(1:(24*14)) 
    P <- 24
    A <- 10 
    y <- A*sin(2*pi*t/P)+20 
    #*****************************************************************************
    par(mfrow = c(2,1))
    plot(t,y,type = "l",xlab = "Time (hours)",ylab = "Amplitude")
    plot.new()
    

    其次,我得到了情节面板的尺寸 . vpp将仅用于ggplot grobs的维度(类似于上面baptiste的想法)

    require(gridBase)
    vps <- baseViewports()
    vpp <- pushViewport(vps$figure,vps$plot) ## here I add a new viewport
    vpp <- current.viewport()
    upViewport(2)
    

    ggplot2将savec绘制为grob表:

    require(ggplot2)
    p <- ggplot(acd, aes(Lag, ACF)) + geom_area(fill = "grey") +
      geom_hline(yintercept = c(0.05, -0.05), linetype = "dashed") +
      theme_bw()
    data <- ggplot_build(p)
    gtable <- ggplot_gtable(data)
    

    我改变了凹凸的尺寸 . (这里为什么解决方案不一般)

    gtable$heights[[2]] <- vpp$height
    gtable$heights[[4]] <- vpp$height
    gtable$widths[[4]]  <- vpp$width
    

    我情节

    grid.draw(gtable)
    

    enter image description here

相关问题