昨晚想到似乎以前在那里见过类似的代码,今天早上狠狠搜了一下 GitHub star 过的项目终于找到了:
theme_Publication_blank <- function(base_size=12, base_family="") {
(theme_foundation(base_size=base_size, base_family=base_family)
+ theme(plot.title = element_text(size = rel(1.2), hjust = 0.5),
text = element_text(),
panel.background = element_rect(fill = "transparent",colour = NA),
plot.background = element_rect(fill = "transparent",colour = NA),
panel.border = element_rect(colour = NA, fill = "transparent"),
axis.title = element_text(size = rel(1)),
axis.title.y = element_text(angle=90,margin=margin(0,10,0,0)),
axis.title.x = element_text(margin=margin(10,0,0,0)),
axis.text = element_text(),
axis.line = element_line(colour="black"),
axis.ticks = element_line(size = 0.3),
axis.line.x = element_line(size = 0.3, linetype = "solid", colour = "black"),
axis.line.y = element_line(size = 0.3, linetype = "solid", colour = "black"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
legend.key = element_rect(colour = NA, fill="transparent"),
legend.position = "bottom",
legend.margin = margin(t = 10, unit='pt'),
plot.margin=unit(c(10,5,5,5),"mm"),
strip.background=element_rect(colour="#d8d8d8",fill="#d8d8d8")
))
}
# Define plot exporting helper function
set_panel_size <- function(p=NULL, g=ggplotGrob(p), file=NULL,
margin = unit(1,"mm"),
width=unit(7, "inch"),
height=unit(5, "inch")){
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)
g$widths[panel_index_w] <- rep(width, nw)
g$heights[panel_index_h] <- rep(height, nh)
if(!is.null(file)) {
ggplot2::ggsave(file, g,
width = convertWidth(sum(g$widths) + margin,
unitTo = "in", valueOnly = TRUE),
height = convertHeight(sum(g$heights) + margin,
unitTo = "in", valueOnly = TRUE), useDingbats=F,
dpi=300)
invisible(g)
}
}
代码仓库在 这里
这里作者首先定义了一个空白主题 theme_Publication_blank
,这在出版物里很常见,主题都力求简洁。然后定义了一个 set_panel_size()
函数,这个函数用来保存图片到 PDF。在使用时可以看到作者使用形如:
# Generate plot
plot <- ggplot(data_long, aes(x = age, y = expression, color = gene)) +
theme_Publication_blank() +
geom_line(aes(linetype=Diagnosis), stat="smooth", size = 2,
method = "loess", span = 0.75, se = FALSE) +
scale_color_manual(values = colors) +
scale_y_continuous(expand = c(0,0)) +
scale_x_continuous(expand = c(0,0)) +
guides(size = "none", alpha = "none") +
ggtitle("CD14+/CD16+/CD68hi\nMonocytes") +
theme(legend.position = "right",
text = element_text(size=24),
legend.key.size = unit(0.5, "in"))
# Export plot
set_panel_size(plot, file = paste0(output_dir,
"apoe_apoc1_pltp_loess_cd68hi_mono.pdf"),
width = unit(5, "inch"), height = unit(3, "inch"))
的代码作图和保存。我正在看 set_panel_size()
这个函数代码,我还没有搞懂这个函数具体是在做什么是什么原理。