将线段添加到现有构面网格ggplot r

时间:2016-04-14 18:48:14

标签: r ggplot2 facet-wrap

我试图在两种不同的栖息地类型(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()

first plot

我想在现有的facet网格中为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)

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

second plot

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

1 个答案:

答案 0 :(得分:1)

如何将主要和次要栖息地组合成一个变量并将该变量映射到美学?

注意我在这里使用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()