r - 将线段添加到现有的小平面网格ggplot r

标签 r ggplot2 facet-wrap

我正在尝试绘制 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()

first plot

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

是否有更好的方法将这些额外的线添加到现有网格(最好是虚线)? 如果有任何帮助,我将不胜感激! 非常感谢,提前!

最佳答案

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

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

关于r - 将线段添加到现有的小平面网格ggplot r,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36631537/

相关文章:

r - FUN(X[[i]], ...) 错误 : object not found when adding geom_text with facet

r - 如何从线性模型的 coef/model.matrix 返回中手动获取 predict() 值

r - 声音数据如何?

r - 绘制一条 geom_smooth 曲线而不是多条曲线

r - 更改图例中值的顺序但保留颜色

r - 在R中使用带有facet_wrap的ggplot2显示多轴标签

r - R中的aes和aes_string(ggplot2)有什么区别

r - 是否可以在 R 中一步复制和修改列表?

r - 具有给定权重向量的ggplot平滑线glm模型

根据因子级别重新格式化标签/保留 ggplot2::facet_wrap() 中多因子构面的顺序