R 如何在多个多面ggplot2图形中实现相同的面大小和比例?
我有一系列的R 如何在多个多面ggplot2图形中实现相同的面大小和比例?,r,ggplot2,R,Ggplot2,我有一系列的ggplot2图形,水平面数量恒定,垂直面数量不同。我想将图片另存为.pdf格式的横向a4格式 然而,我不知道如何才能获得相同比例的面。如果我尝试手动调整它,并针对不同数量的垂直面改变宽度和高度,则绘图之间的比例会有所不同,即,我得到不同的点大小和线宽 本质上,对于具有可变数量(垂直)面的绘图,如何实现相同的面大小和比例 以下是一个例子: df <- expand.grid(a = 1:2, b = 1:5, x = 1:10) df$y <- df$x plot <
ggplot2
图形,水平面数量恒定,垂直面数量不同。我想将图片另存为.pdf格式的横向a4格式
然而,我不知道如何才能获得相同比例的面。如果我尝试手动调整它,并针对不同数量的垂直面改变宽度
和高度
,则绘图之间的比例会有所不同,即,我得到不同的点大小和线宽
本质上,对于具有可变数量(垂直)面的绘图,如何实现相同的面大小和比例
以下是一个例子:
df <- expand.grid(a = 1:2, b = 1:5, x = 1:10)
df$y <- df$x
plot <- ggplot(data = df, mapping = aes(x = x, y = y)) +
geom_point()
plot1 <- plot + facet_grid(facets = "a ~ b")
plot2 <- plot + facet_grid(facets = ". ~ b")
ggsave(filename = "./figures/plot1.pdf", plot = plot1,
height = 210, width = 297, units = "mm")
ggsave(filename = "./figures/plot2.pdf", plot = plot2,
height = 210, width = 297, units = "mm")
df我使用此代码将面板大小设置为绝对值,可能在这里有所帮助
set_panel_size <- function(p=NULL, g=ggplotGrob(p), file=NULL,
margin = unit(1,"mm"),
width=unit(4, "cm"),
height=unit(4, "cm")){
panels <- grep("panel", g$layout$name)
panel_index_w<- unique(g$layout$l[panels])
panel_index_h<- unique(g$layout$t[panels])
nw <- length(panel_index_w)
nh <- length(panel_index_h)
if(getRversion() < "3.3.0"){
# the following conversion is necessary
# because there is no `[<-`.unit method
# so promoting to unit.list allows standard list indexing
g$widths <- grid:::unit.list(g$widths)
g$heights <- grid:::unit.list(g$heights)
g$widths[panel_index_w] <- rep(list(width), nw)
g$heights[panel_index_h] <- rep(list(height), nh)
} else {
g$widths[panel_index_w] <- rep(width, nw)
g$heights[panel_index_h] <- rep(height, nh)
}
if(!is.null(file))
ggsave(file, g,
width = convertWidth(sum(g$widths) + margin,
unitTo = "in", valueOnly = TRUE),
height = convertHeight(sum(g$heights) + margin,
unitTo = "in", valueOnly = TRUE))
invisible(g)
}
print.fixed <- function(x) grid.draw(x)
set\u panel\u size此函数复制到egg::set\u panel\u size()