无法将元素添加到图例 (iNEXT / ggplot2)

Trouble adding elements to legend (iNEXT / ggplot2)

我使用 R 中的 iNEXT 包制作了稀疏曲线并添加了两条水平线 手动绘制两条曲线的渐近线(包不这样做,所以我尝试使用 ggplot 函数并且它似乎有效),此外我扩展了 x/y 轴。 不幸的是,我的技能显然太有限,无法弄清楚如何在下面的图例中添加渐近线,标记为 "Asymptotes: North and South"(或类似的东西)。 非常感谢您的帮助。我在下面添加了我的代码和图表作为图片,如果有什么遗漏,请告诉我!

祝身体健康!

### Rarefaction with iNEXT -> Species X Visits incidence_frequency data

# List for both regions
incidence_freq_north <- c(7,2,0,0,4,0,2,0,2,1,0,0,0,6,0,1,1,0,0,0)
incidence_freq_south <- c(23,0,0,1,9,2,0,4,1,1,1,2,6,1,4,1,0,8,2,7,1)

list_rarefaction_freq = list(North = incidence_freq_north, South = incidence_freq_south)

## create output file
out_freq <- iNEXT(list_rarefaction_freq, q=0, datatype="incidence_freq", endpoint=NULL,
             size=NULL, knots=400, se=TRUE, conf=0.95, nboot=400)

# Sample-size-based R/E curves, separating plots by "order"
ggiNEXT(out_freq, type=1, facet.var="order") +
  ylim(c(0,40)) + xlim(c(0,70)) + 
  theme_bw(base_size = 18) + 
  geom_hline(yintercept=24, linetype="solid", color = "darkslategray2") + 
  geom_hline(yintercept=10, linetype="solid", color = "coral1")

Graph as image

我认为一个可能的解决方案是自己绘制 ggiNEXT 图(他们在这里提供了一个教程:https://cran.r-project.org/web/packages/iNEXT/vignettes/Introduction.html

然后,您可以添加一个对应于渐近线值的新数据框,并使用 ggnewscale 包中的 new_color_scale 函数在您的图表上添加一个新的色标:

df <- fortify(out_freq, type =1)

df.point <- df[which(df$method=="observed"),]
df.line <- df[which(df$method!="observed"),]
df.line$method <- factor(df.line$method, 
                         c("interpolated", "extrapolated"),
                         c("interpolation", "extrapolation"))

df.asympote <- data.frame(y = c(24,10),
                          Asymptote = c("North","South"))


library(ggnewscale)

ggplot(df, aes(x=x, y=y, colour=site)) + 
  geom_point(aes(shape=site), size=5, data=df.point) +
  geom_line(aes(linetype=method), lwd=1.5, data=df.line) +
  geom_ribbon(aes(ymin=y.lwr, ymax=y.upr,
                  fill=site, colour=NULL), alpha=0.2) +
  labs(x="Number of individuals", y="Species diversity") +
  scale_color_discrete(name = "Site")+
  scale_shape_discrete(name = "Site")+
  scale_fill_discrete(name = "Site")+
  scale_linetype_discrete(name = "Method")+
  theme_bw(base_size = 18)+
  new_scale_color()+
  geom_hline(data = df.asympote, aes(yintercept = y, color = Asymptote))

它是否回答了您的问题?