将空图添加到小平面,并与另一个小平面结合

时间:2018-03-15 16:04:32

标签: r ggplot2 facet facet-wrap cowplot

使用此SO solution我创建了一个带有两个“空”图的构面,目的是与另一组facet_wrap图组合,如下所示。目的是为不同的单位测量设置两个y轴标签。如何使网格布局看起来像顶部图像,它产生我想要的排列,但不是轴标签?这是通过plot_grid以单独的图完成的。我的当前输出无法正确缩放并与其他绘图重叠,如第二张图中所示,但提供了轴标签。 我下面有示例数据,只需复制并运行代码即可输入。 enter image description here

enter image description here

library(ggplot2)
library(grid)
library(cowplot)

clipboard <- readClipboard()
test.data <- read.table(file = "clipboard", sep = ",", header=TRUE)
test.data1 <- test.data[1:24, ]
test.data2 <- test.data[25:32, ]

testplot1 <- ggplot(test.data1, aes(Station, value)) +
  geom_point() +
  labs(x = "Stations", y = "Scale A") +
  theme(legend.position = "none", legend.title = element_blank()) +
  facet_wrap( ~ constituent, ncol = 3, scales = "free_y")

testplot2 <- ggplot(test.data2, aes(Station, value)) +
  geom_point() +
  labs(x = "Stations", y = "Scale B") +
  theme(legend.position = "none", legend.title = element_blank(), axis.title.y = element_text(hjust = 0.2)) +
  facet_wrap( ~ constituent, ncol = 1, scales = "free_y")

blankplots <- ggplotGrob(testplot2)
rm_grobs <- blankplots$layout$name %in% c("panel-1-1", "panel-2-1", "strip-t-1-1", "strip-t-1-2")
blankplots$grobs[rm_grobs] <- NULL
blankplots$layout <- blankplots$layout[!rm_grobs, ]
grid.newpage()
emptygrids <- grid.draw(blankplots)

plot_grid(emptygrids, MPLOOplot1)

示例日期如下:

Station,constituent,value
A1,A,1
B1,A,1
A1,B,2
B1,B,2
A1,C,3
B1,C,3
A1,D,4
B1,D,4
A1,E,5
B1,E,5
A1,F,6
B1,F,6
A1,G,7
B1,G,7
A1,H,8
B1,H,8
A1,I,9
B1,I,9
A1,J,10
B1,J,10
A1,K,11
B1,K,11
A1,L,1.4
B1,L,1.4
A1,Blank1,NA
B1,Blank1,NA
A1,Blank2,NA
B1,Blank2,NA
A1,XX,0.52
B1,XX,0.52
A1,YY,0.355
B1,YY,0.355

1 个答案:

答案 0 :(得分:3)

我不确定我到底知道你要做什么,所以让我知道这是你的想法。我不确定你想要将颜色映射到什么,所以我在本例中使用了constituent

library(gridExtra)
library(ggplot2)
library(dplyr)
library(cowplot)
theme_set(theme_classic())

testplot1 <- ggplot(test.data1, aes(Station, value, colour=constituent)) +
  geom_point() +
  labs(x = "Stations", y = "Scale A") +
  theme(legend.title = element_blank()) +
  facet_wrap( ~ constituent, ncol = 3, scales = "free_y") +
  guides(colour=guide_legend(ncol=2))

testplot2 <- ggplot(test.data2 %>% filter(!grepl("Blank", constituent)), 
                    aes(Station, value, colour=constituent)) +
  geom_point() +
  labs(x = "Stations", y = "Scale B") +
  theme(legend.title = element_blank(), 
        axis.title.y = element_text(hjust = 0.2)) +
  facet_wrap( ~ constituent, ncol = 1, scales = "free_y")

leg1 = get_legend(testplot1)
leg2 = get_legend(testplot2)

testplot1 = testplot1 + guides(colour=FALSE)
testplot2 = testplot2 + guides(colour=FALSE)

现在我们用grid.arrange列出情节和图例。这需要手动调整高度和宽度。

grid.arrange(
  arrangeGrob(
    arrangeGrob(nullGrob(), leg2, leg1, nullGrob(), ncol=4, widths=c(1,4,4,1)),
    testplot2, ncol=1, heights=c(4.2,5)
    ),
  testplot1, ncol=2, widths=c(1.1,3))

enter image description here