将标签添加到ggplot行而不是点

时间:2020-07-12 06:15:10

标签: r ggplot2 dplyr label

我有一个物种频率的数据框。我正在绘制随着时间变化的丰度,并想标记最常见的物种。我有一个包含以下五列的数据框-日期,种类,频率,部位,治疗。目前,我正在按照以下方式进行操作:

df %>%
  mutate(majorSpp = ifelse(frequency > 0.4, as.character(species), "")) %>% 
  ggplot(aes(x = date, y = frequency, colour = species, group = species)) +
    geom_line() +
    facet_grid(type ~ treatment)
    geom_label_repel(aes(label=majorSpp))

但是,这种方法意味着,如果一个物种在多个日期上的频率大于0.4,则在多个点中的每个点上标记该线,而不仅仅是一次。我需要的是,仅在该物种的所有测量日期中该物种的频率最高的点上为其指定一个物种名称。但是我还不太清楚如何将这种逻辑融入变异函数中。

如果可以轻松实现其他包装中的开箱即用,我可以使用其他标签解决方案,例如directlabel。

编辑:

示例数据:

df <- data.frame(date = c(01-02-2020, 01-02-2020, 04-04-2020, 04-04-2020), 
                 species = c("cat", "dog", "cat", "dog"), 
                 frequency = c(0.1, 0.5, 0.6, 0.5),
                 site = c('a', 'a', 'a', 'a'),
                 treatment = c(1, 1, 1, 1))

如果我为高于0.4的任何频率创建标签,则会为“狗”生成两个标签。我要这样做的原因是我大约有50种,但是大多数情况下大多数频率为零。因此,使用颜色和图例之类的东西是没有用的。

部分解决方案:

df %>%
  mutate(majorSpp = ifelse(frequency > 0.4, as.character(species), "")) -> temp
temp$majorSpp[duplicated(temp$majorSpp)] <- NA
temp %>%
    ggplot ...

这有两个问题,如果您用附加的列进行构面,则在整个绘图中每个majorSpp仅显示一次,而理想情况下,在频率高于0.4的每个构面中都将显示一次。其次,不是很重要,它破坏了良好的管道流动。

我在下面附上了使用部分解决方案生成的图的图片:enter image description here

2 个答案:

答案 0 :(得分:1)

我不确定这是否有帮助,但是如果我了解您是否正在寻找类似的东西?让我知道这如何适合您的问题:

#Data
mdf <- structure(list(date = c(-2021, -2021, -2020, -2020, -2021, -2021, 
-2020, -2020), species = structure(c(1L, 2L, 1L, 2L, 1L, 2L, 
1L, 2L), .Label = c("cat", "dog"), class = "factor"), frequency = c(0.1, 
0.5, 0.6, 0.5, 0, 0, 0, 0), a_bunch_of_other_cols = structure(c(2L, 
3L, 4L, 1L, 2L, 3L, 4L, 1L), .Label = c("a", "x", "y", "z"), class = "factor")), row.names = c(NA, 
-8L), class = "data.frame")

#Code
mdf %>%
  mutate(majorSpp = ifelse(frequency > 0.4, as.character(species), "")) %>% 
  ggplot(aes(x = date, y = frequency, colour = species, group = species)) +
  geom_point() +
  geom_line()+
  geom_label_repel(aes(label=majorSpp),show.legend = F)+
  facet_wrap(~a_bunch_of_other_cols)

enter image description here

答案 1 :(得分:0)

我不知道的秘密调味料是“ group_by”。请注意,summary摆脱了分组,因此您需要重新添加。

df %>%
  filter(morphology != "inanimate") %>%
  group_by(type, date, treatment, species) %>%
  summarise(av = mean(presence), morphology = unique(morphology)) %>%
  group_by(treatment, type) %>%
  mutate(majorSpp = ifelse(av > 0.6, as.character(species), "")) %>%
  mutate(majorSpp = ifelse(duplicated(majorSpp), '', majorSpp)) %>%
  ungroup(treatment, type) %>%
  ggplot(aes(x = date, y = av, colour = morphology, group = species)) +
    geom_line() +
    facet_grid(treatment ~ type) +
    geom_label_repel(aes(label=majorSpp), size=2)

制作:

enter image description here