gpt4 book ai didi

r - Plot grid/ggplot2 + base with pdf 给出空白的第一页(控制图宽度)

转载 作者:行者123 更新时间:2023-12-04 17:38:51 27 4
gpt4 key购买 nike

我想在 pdf 输出的同一个图中绘制网格和基本图。我看到了如何在几个地方添加网格加底,包括这里:Combining grid.table and base package plots in R figureR put together traditional plot and ggplot2

我还想使用比例或相对宽度来控制绘图的宽度。我以为我有下面的代码,我试图输出到 pdf,然后它在绘图之前打印一个空白页。我怎样才能让它不绘制空白页?我没有与任何包结婚,我只是希望答案可以概括(简单是一个加号;我觉得我下面的代码可以简化)。

library(ggplot2); library(grid); library(gridBase)

pdf("test.pdf")

grid::grid.newpage()
grid::pushViewport(grid::viewport(layout = grid::grid.layout(1, ncol=2,
widths = grid::unit(c(.6, .4), "npc"))))

#Draw base plot
grid::pushViewport(grid::viewport(layout.pos.col = 1, width = grid::unit(.8, "npc")))

graphics::plot.new()
graphics::par(fig = gridBase::gridFIG(), mar=c(1, 1, 1, 1), new = TRUE)


plot(1:10)

grid::popViewport()

#Draw ggplot
grid::pushViewport(grid::viewport(layout.pos.col = 2, width = grid::unit(.2, "npc")))
print( ggplot(mtcars, aes(mpg, hp)) + geom_point(), newpage = FALSE)
grid::popViewport()

dev.off()

情节看起来像:

enter image description here

最佳答案

使用 gridGraphics 包可能会更好,尽管事情也不是一帆风顺,

enter image description here

library(gridGraphics)

grab_grob <- function(){
grid.echo(newpage=TRUE)
grid.grab()
}

par(mar=c(4,6,1,1)) # for some reason need lots of space
plot(1:10)
bg <- grab_grob()
p <- ggplot(mtcars, aes(mpg, hp)) + geom_point()

ggsave("test.pdf", gridExtra::arrangeGrob(bg, p, widths = c(2,1)))

关于r - Plot grid/ggplot2 + base with pdf 给出空白的第一页(控制图宽度),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35423018/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com