我正在尝试绘制2种不同栖息地类型(hab 1和hab 2)之间的物种分布。其次,我的某些物种使用了某些栖息地,因此我有一个单独的列用于次要hab1(hab1.sec)。为了可视化它们在两个栖息地和不同深度之间的分布,我在hab1和hab2之间使用facet_grid。示例代码如下:

# example code
set.seed(101)
ID <- seq(1,20, by=1)  ## ID for plotting
species <- sample(letters, size=20)  ## arbitrary species

## different habitat types in hab.1
hab1 <- c("coastal","shelf","slope","open.ocean","seamount")
hab1.pri <- sample(hab1, size = 20, replace = T)

## secondarily used habitats, may not be present for some species
hab.sec <- c("coastal","shelf","slope","open.ocean","seamount", NA)
hab1.sec <- sample(hab.sec, size = 20, replace = T)

## habitat types for hab.2
hab2 <- c("epipelagic","benthopelagic","epibenthic","benthic")
hab.2 <- sample(hab2, size = 20, replace = T)

## arbitrary depth values
dep.min <- sample(seq(0,1000), size = 20, replace = T)
dep.max <- sample(seq(40, 1500), size = 20, replace = T)

# make data frame
dat <- data.frame(ID, species, hab1.pri, hab1.sec, hab.2,dep.min, dep.max)

# ggplot with facet grid
p <- ggplot(data=dat)+ geom_segment(aes(x=as.factor(ID),xend=as.factor(ID),y=dep.min, yend=dep.max),size=2,data = dat)+ scale_y_reverse(breaks = c(0, 200, 1000,1500))+facet_grid(hab.2~hab1.pri, scales = "free" ,space = "free")+theme_bw()

我想在现有构面网格中为hab1.sec添加细分。我已经试过这段代码:
p+ geom_segment(aes(x=as.factor(ID),xend=as.factor(ID),y=dep.min, yend=dep.max),linetype=2,data = dat)+facet_wrap(~hab1.sec)

但是这样做会产生一个新图。

有没有更好的方法将这些额外的线添加到现有网格(最好是虚线)?
我将非常感谢您对此提供的任何帮助!
非常感谢,提前!

最佳答案

将主要和次要栖息地合并为一个变量,然后将该变量映射为美学,该怎么办?

注意,我在这里使用tidyrdplyr工具,因为它们在这种情况下有很大帮助。

library(dplyr)
library(tidyr)

dat %>%
  gather(hab1, value, -ID, -species, -(hab.2:dep.max)) %>%
  ggplot()+
  geom_segment(aes(x=as.factor(ID),xend=as.factor(ID),y=dep.min, yend=dep.max, linetype=hab1),size=2) +
  scale_y_reverse(breaks = c(0, 200, 1000,1500))+
  facet_grid(hab.2~value, scales = "free" ,space = "free")+
  theme_bw()

08-06 19:27