电子说
使用R拼出这样的一张图:
customLayout
包install.packages("customLayout")
# or
library(devtools)
install_github("zzawadz/customLayout")
简单介绍一下 customLayout
包:
lay_new(mat, widths, heights)
lay_show(lay)
lay_bind_row(lay1, lay2, ..., heights)
lay_bind_col(lay1, lay2, ..., widths)
lay_split_field(lay1, lay2, field = idx)
lay_set(lay)
lay_grid(grobs, lay)
有了这些功能,基本上就可以满足拼图需求了。
首先根据效果图将图进行分区并且编号,方便制定排版方案,编号规则为从上到下,从左到右
编号之后应该是这样的:
然后确定排版方案:
每大部分内部按行合并,最后将三部分按列合并,并且在排列的时候注意比例。
p3 = p4 = p5 = p6 = lay_new(matrix(1))
lay56 = lay_bind_row(p5, p6, heights = c(1, 1))
lay3456 = lay_bind_col(lay_bind_col(p3, p4, widths = c(2, 4)), lay56, widths = c(6, 3))
lay_show(lay3456)
lay127 = lay_new(matrix(1:4, nrow = 2), heights = c(6, 3), widths = c(6, 9))
lay_show(lay127)
lay_res = lay_split_field(lay127, lay3456, field = 3)
lay_show(lay_res)
这样布局就已经画好了,接下来直接填图就行了。
先画个简单的快速看下效果:
pdf("customLayout1.pdf", 13, 9)
lay_set(lay_res)
plot(1:10)
plot(1:10)
plot(1:10)
plot(1:10)
plot(1:10)
plot(1:10)
plot(1:10)
dev.off()
再画个像样点的并测试能不能合并ggplot对象:
# test customLayout
library("customLayout")
library("ggplot2")
data = iris
colnames(data) = LETTERS[1:ncol(data)]
# plot lay3456
p3 = p4 = p5 = p6 = lay_new(matrix(1))
lay56 = lay_bind_row(p5, p6, heights = c(1, 1))
lay3456 = lay_bind_col(lay_bind_col(p3, p4, widths = c(2, 4)), lay56, widths = c(6, 3))
lay_show(lay3456)
# plot lay127 and lay_res
lay127 = lay_new(matrix(1:4, nrow = 2), heights = c(6, 3), widths = c(6, 9))
lay_show(lay127)
lay_res = lay_split_field(lay127, lay3456, field = 3)
lay_show(lay_res)
# fill lay
p1 <- ggplot(data, aes(A, B)) + geom_point(colour = "#dd1c77")
p2 <- ggplot(data, aes(A)) + geom_histogram(binwidth = 0.1, colour = "#dd1c77", fill= "#dd1c77")
p3 <- ggplot(data, aes(B)) + geom_density(alpha = 0.2, colour = "#dd1c77", fill = "white", size = 2)
p4 <- ggplot(data, aes(A, B, fill = C)) + geom_tile()
p5 <- ggplot(data[data[, "E"] == "setosa",], aes(y = C)) + geom_boxplot(colour = "#dd1c77", size = 2)
p6 <- ggplot(data[data[, "E"] == "versicolor",], aes(y = C)) + geom_boxplot(colour = "#dd1c77", size = 2)
p7 <- ggplot(data, aes(x = B, y = C)) + geom_line(colour = "#dd1c77", size = 2)
pdf("customLayout2.pdf", 13, 9)
plots2 = lapply(c(1:7), function(x) get(paste0("p", x)))
lay_grid(plots2, lay_res)
dev.off()
另外发现基础包的图和ggplot2的图不能合并,不过一般也不会用基础包来画图~
全部0条评论
快来发表一下你的评论吧 !