gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 14:08:36 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com