gpt4 book ai didi

r - 在 ggplot2 中设置切面的绝对大小

转载 作者:行者123 更新时间:2023-12-03 22:31:18 26 4
gpt4 key购买 nike

我正在为报告创建几个分面图。刻面的数量在 2 到 8 个之间变化。理想情况下,我希望每个刻面的绝对大小(跨图)相同(例如 4x4 厘米),以便更容易比较它们(而且看起来也更好) )。

那可能吗?

df1 <- structure(list(group1 = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,1L, 1L, 1L, 1L, 1L), .Label = c("S1", "S2"), class = "factor"), group = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L), .Label = c("A", "B", "C", "D", "E"), class = "factor"), value = 1:12), class = "data.frame", row.names = c(NA, -12L), .Names = c("group1", "group", "value"))

df2 <- structure(list(group1 = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("S1", "S2"), class = "factor"), group = structure(c(4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L), .Label = c("A", "B", "C", "D", "E"), class = "factor"), value = 13:20), class = "data.frame", row.names = c(NA, -8L), .Names = c("group1", "group", "value"))

library(ggplot2)

plot1 <- ggplot(df1) + geom_histogram(aes(x=value)) + facet_wrap(~group)
plot2 <- ggplot(df2) + geom_histogram(aes(x=value)) + facet_wrap(~group)

enter image description here
enter image description here

最佳答案

为此,我使用了以下功能,

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 = grid::convertWidth(sum(g$widths) + margin,
unitTo = "in", valueOnly = TRUE),
height = grid::convertHeight(sum(g$heights) + margin,
unitTo = "in", valueOnly = TRUE))

g
}

g1 <- set_panel_size(plot1)
g2 <- set_panel_size(plot2)
gridExtra::grid.arrange(g1,g2)

enter image description here

关于r - 在 ggplot2 中设置切面的绝对大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32580946/

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