我已经生成了一个结合了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”)获得。附图显示了结果。 然而,两个面板的尺寸不匹配,即第二面板似乎比第一面板略宽。如何在不必使用
手动设置边距的情况下克服此问题pushViewport(plotViewport(c(4,1.2,0,1.2)))
答案 0 :(得分:6)
这应该给你一些提示:
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中做所有事情?
答案 1 :(得分:3)
主要思想是推送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)