如何解决如何基于使用两个因素的因素水平在facet_wrap中打破新行?
如何使每个新行都以新的因子水平开头? 当前,它基于批次和样本进行包装,但不会在新的批次因子水平上中断。 尝试“ facet_grid(〜batch〜sample)”时,有很多不需要的空白面板。
R的结果和Photoshop的期望结果。
经过编辑以包含较小的可重复数据集
df <- data.frame("sample" = c("A1","A2","A3","A4","A5","A6","A7","A8","A9","A10","A11"),"length_um" = c(1.8,1.9,0.52,0.75,0.14,0.95,0.84,0.46,0.25,0.13,0.31),"breadth_um" = c(1.44,1.52,0.41,0.60,0.12,0.76,0.68,0.37,0.20,0.11,0.25),"batch" = c("batch01","batch01","batch02","batch03","batch03"))
df <- df %>%
mutate_if(sapply(df,is.character),as.factor)
ggplot(df,aes(x=length_um,y=breadth_um)) +
geom_point()+
facet_wrap(~batch~sample)
解决方法
尝试将facet_wrap(~batch~sample)
替换为facet_grid(~batch~sample)
。
现在还做不到吗?我能想象的唯一解决方案是按“批处理”变量拆分数据帧,并排列生成的多图。从 this post 重写的代码。我想要一个集成的 facet_wrap 参数来让它更干净
library(ggplot2)
library(cowplot)
library(dplyr)
# Sample dataframe
df = data.frame(
sample = c('A1','A2','A3','A4','A5','A6','A7','A8','A9','A10','A11'),length_um = c(1.8,1.9,0.52,0.75,0.14,0.95,0.84,0.46,0.25,0.13,0.31),breadth_um = c(1.44,1.52,0.41,0.60,0.12,0.76,0.68,0.37,0.20,0.11,0.25),batch = c('batch01','batch01','batch02','batch03','batch03')
)
# Set factors to facet
facet = c('batch','sample')
# Maximum number of levels
n_facet_max = split(df,df[[facet[1]]]) %>%
lapply(function(x) n_distinct(x[[facet[2]]])) %>%
unlist() %>%
max()
# Plot function
my_fun = function(x) {
plot_tmp = ggplot(x,aes(x = length_um,y = breadth_um)) +
geom_point()+
facet_grid(
x[[facet[1]]] ~ x[[facet[2]]]
)
n_facet = n_distinct(x[[facet[2]]])
if (n_facet < n_facet_max) {
plot_tmp = plot_grid(
NULL,plot_tmp,axis = 'tb',ncol = 2,rel_widths = c(n_facet_max - n_facet,n_facet)
)
}
return(plot_tmp)
}
# Plot per 'batch' variable
plot_ls = split(df,df[[facet[1]]]) %>% lapply(function(x) my_fun(x))
# Layout
plot_grid(
plotlist = plot_ls,ncol = 1,axis = 'r'
)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。