3

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

在此处输入图像描述

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
4

1 回答 1

4

我不确定我是否完全理解你想要做的事情,所以如果这就是你的想法,请告诉我。我不确定你想要将颜色映射到什么,所以我只是用于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))

在此处输入图像描述

于 2018-03-15T17:30:27.350 回答