我有两个图,我试图与双 y 轴合并。我很难摆脱我试图合并的两个传说之间的空间。这是我的两个图表:
require(ggplot2)
download.file("https://www.dropbox.com/s/y6qg4432x2l2hbr/data1.csv?dl=1","data1.csv")
download.file("https://www.dropbox.com/s/jv5iuarx1qa3vzf/data2.csv?dl=1","data2.csv")
data1<-read.csv("data1.csv")
data2<-read.csv("data2.csv")
> head(data1) # https://www.dropbox.com/s/y6qg4432x2l2hbr/data1.csv?dl=1
base pos type values labels valueme2
1 A 1 mean_r 1.0200473 2771 13.56172
2 A 1 quant_r 0.6450000 2771 13.56172
4 C 1 mean_r 6.1059971 343 56.25043
5 C 1 quant_r 3.5411200 343 56.25043
7 G 1 mean_r 0.9848452 84 13.26626
8 G 1 quant_r 0.5639600 84 13.26626
> head(data2) # https://www.dropbox.com/s/jv5iuarx1qa3vzf/data2.csv?dl=1
base pos type values labels valueme2
3 A 1 p_val 0.7653560 2771 13.56172
6 C 1 p_val 51.2504280 343 56.25043
9 G 1 p_val 0.3350526 84 13.26626
12 T 1 p_val 2.0327415 2770 13.56881
15 A 2 p_val 51.2504280 343 56.25043
18 C 2 p_val 0.5417566 484 13.27813
prettify <- theme(panel.background = element_rect(fill = NA),
panel.grid.major.y = element_blank(),
panel.grid.major.x = element_line(size=.1, color="gray",linetype="dotted"),
panel.grid.minor.y = element_blank(),
panel.grid.minor.x = element_line(size=.1, color="gray"))
graphme1 <- ggplot(data1, aes(x = base, y = values, colour = type, group = type)) +
geom_line(size=1.3) + facet_wrap( ~ pos, ncol = 7) +
scale_color_manual(values=c("#7CAE00", "#00BFC4")) +
theme_bw() %+replace% prettify +
theme(legend.position="bottom")
graphme2 <- ggplot(data2, aes(x = base, y = values, colour = "p_val", group = type)) +
geom_text(aes(y=(valueme2 + 0.3),label = labels, size = 1), colour="black",alpha=0.65,show_guide=F) +
geom_line(size=1.3) + facet_wrap( ~ pos, ncol = 7) +
theme_bw() %+replace% prettify +
theme(legend.position="bottom")
下面是我如何合并两者:
g1 <- ggplot_gtable(ggplot_build(graphme1))
g2 <- ggplot_gtable(ggplot_build(graphme2))
pp <- c(subset(g1$layout, grepl("panel",name) , se = t:r))
g <- gtable_add_grob(g1, g2$grobs[grep("panel",g2$layout$name)], pp$t, pp$l, pp$b, pp$l)
ia <- which(grepl("axis_l",g2$layout$name) | grepl("axis-l",g2$layout$name) )
ga <- g2$grobs[ia]
axis_idx <- as.numeric(which(sapply(ga,function(x) !is.null(x$children$axis))))
for(i in 1:length(axis_idx)){
ax <- ga[[axis_idx[i]]]$children$axis
ax$widths <- rev(ax$widths)
ax$grobs <- rev(ax$grobs)
ax$grobs[[1]]$x <- ax$grobs[[1]]$x - unit(0.9, "npc") + unit(0.16, "cm")
g <- gtable_add_cols(g, g2$widths[g2$layout[ia[axis_idx[i]], ]$l], length(g$widths) - 1)
g <- gtable_add_grob(g, ax, pp$t[axis_idx[i]], length(g$widths) - i, pp$b[axis_idx[i]])
}
leg1 <- g1$grobs[[which(g1$layout$name == "guide-box")]]
leg2 <- g2$grobs[[which(g2$layout$name == "guide-box")]]
g$grobs[[which(g$layout$name == "guide-box")]] <- gtable:::cbind_gtable(leg1, leg2, "first")
grid.newpage()
grid.draw(g)
图形1
图形2
合并
在最后一张图片中,您可以看到我试图合并的两个图例之间的差距。如果可能的话,我还想摆脱“p_val”标题并将两个图例组合在一个名称“type”下