我正在尝试使用facet_wrap创建一些多图。但是,我不确定是否适合我的图表。这是一个简短的可复制示例:
ggplot(airquality, aes(x = Day, y = Temp)) +
facet_wrap(~Month) +
geom_line()
这将在此处生成该图:
是否可以使用facet_wrap方法“居中”第二行中的两个图? 请注意,我不想对图进行重新排序,只想将第二行居中
答案 0 :(得分:3)
@Tjebo关于使用cowplot
的建议将起作用:
p <- ggplot(mapping = aes(x = Day, y = Temp)) +
facet_wrap(~Month) +
geom_line()
cowplot::plot_grid(
p %+% subset(airquality, Month < 8),
p %+% subset(airquality, Month > 7),
nrow = 2
)
答案 1 :(得分:3)
您还可以考虑使用egg
软件包中的函数set_panel_size
,该函数可让您将多个绘图的面板大小(宽度,高度)设置为绝对测量值,有关更多信息,请参见this vignette详细信息。
使用Axeman的代码创建绘图
library(egg)
library(gridExtra)
p <- ggplot(mapping = aes(x = Day, y = Temp)) +
facet_wrap(~Month) +
geom_line()
p1 <- p %+% subset(airquality, Month < 8) + labs(x = NULL)
p2 <- p %+% subset(airquality, Month > 7)
现在在指定面板尺寸后使用grid.arrange
布置图
grid.arrange(grobs = lapply(
list(p1, p2),
set_panel_size,
width = unit(5, "cm"),
height = unit(4, "cm")
))
答案 2 :(得分:1)
以防万一有人想知道如何从头开始在网格中做这件事...
library(ggplot2)
library(dplyr)
library(grid)
vps <- c("top_left", "top_mid", "top_right", "bottom_left", "bottom_right")
main_vp <- vpTree(viewport(name = "main"), vpList(
viewport(x = 1/6, y = 0.75, width = 1/3, height = 0.5, name = vps[1]),
viewport(x = 3/6, y = 0.75, width = 1/3, height = 0.5, name = vps[2]),
viewport(x = 5/6, y = 0.75, width = 1/3, height = 0.5, name = vps[3]),
viewport(x = 1/3, y = 0.25, width = 1/3, height = 0.5, name = vps[4]),
viewport(x = 2/3, y = 0.25, width = 1/3, height = 0.5, name = vps[5])))
grid.newpage()
pushViewport(main_vp)
plots <- lapply(1:5, function(i){
seekViewport(vps[i])
invisible(grid.draw(ggplotGrob(
ggplot(filter(airquality, Month == levels(as.factor(airquality$Month))[i]),
mapping = aes(Day, Temp)) +
geom_line() +
facet_grid(.~Month)
)))})
由reprex package(v0.3.0)于2020-07-03创建