【问题标题】:adding line segments to existing facet grid ggplot r将线段添加到现有的分面网格ggplot r
【发布时间】:2016-04-14 18:48:14
【问题描述】:

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

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

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

【问题讨论】:

  • this answer 的方法在这里可能很好用。
  • 感谢@aosmith 回复!你的意思是p + facet_grid(.~g, margins=TRUE) 部分吗?不幸的是,它对我不起作用..
  • 否,在第二个 geom_segment 调用中从数据集中删除第二个分面变量。这很容易,但我不确定你的最终结果应该是什么样子,所以无法判断它是否有效。

标签: r ggplot2 facet-wrap


【解决方案1】:

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

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

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()

【讨论】:

  • 嘿@boshek,这真的很整洁!是的,我想将两者结合在一起,但我不知道哪个包是最好的工具..尝试使用来自reshape2的melt,但不知道如何使它工作..我可以打扰一下请您提供另一个小细节..是否可以根据hab1而不是colour更改linetype?非常感谢!
  • 当然。只需将colour 更改为linetype。花一些时间与dplyr 和tidyr。它会改变你的生活。
猜你喜欢
  • 2021-04-16
  • 2021-08-07
  • 1970-01-01
  • 2017-10-11
  • 1970-01-01
  • 2016-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多