带有 geom_label_repel 的文本颜色

jer*_*erH 1 r ggplot2 ggrepel

不特定于任何特定的代码段,是否有一种相对简单的方法来更改 geom_label_repel 框中的文本颜色?

具体来说,我有生成以下图表的代码

在此处输入图片说明

标签框中的百分比是最近一周的 7 天移动平均线与前一周相比的百分比变化。我只想在值为正时将文本着色为红色,在值为负时将其着色为绿色。

此图表的数据框可以从这里复制。

情节代码是

#endpoint layer
BaseEndpoints <- smDailyBaseData %>% filter(Base %in% AFMCbases) %>%
  group_by(Base) %>%
  filter(DaysSince == max(DaysSince)) %>%
  select(Base, abbv, DaysSince, newRate,label) %>%
  ungroup()

ZoomEndpoints <- BaseEndpoints %>% filter(Base != 'Edwards') %>%
  mutate(zoom = TRUE)
CAEndPoint <- BaseEndpoints %>% filter(Base == 'Edwards') %>%
  mutate(zoom = FALSE)

ZoomEndpoints <- rbind(ZoomEndpoints, CAEndPoint)

BasePlot <- smDailyBaseData %>% filter(Base %in% AFMCbases) %>%
  ggplot(mapping = aes(x = as.numeric(DaysSince), y = newRate)) +
  geom_line(aes(color=abbv),show.legend = FALSE) +
  scale_color_ucscgb() +
 geom_point(data = BaseEndpoints,size = 1.5,shape = 21, 
            aes(color = abbv,fill = abbv), show.legend = FALSE) +
 geom_label_repel(data=ZoomEndpoints, aes(label=label), show.legend = FALSE,
                   vjust = 0, xlim=c(105,200), size=3, direction='y') +
  labs(x = "Days Since First Confirmed Case", 
       y = "% Local Population Infected Daily") +
  theme(plot.title = element_text(size = rel(1), face = "bold"),
        plot.subtitle = element_text(size = rel(0.7)),
        plot.caption = element_text(size = rel(1))) +
  facet_zoom(xlim = c(50,120), ylim=c(0,0.011),zoom.data=zoom)



print(BasePlot)
Run Code Online (Sandbox Code Playgroud)

All*_*ron 5

是的,就这么简单:

library(ggplot2)

df <- data.frame(x = c(-1, -1, 1, 1), y = c(-1, 1, 1, -1), value = c(-2, -1, 1, 2))

ggplot(df, aes(x, y)) + 
  geom_point(size = 3) +
  ggrepel::geom_label_repel(aes(label = value, colour = factor(sign(value)))) +
  lims(x = c(-100, 100), y = c(-100, 100))  +
  scale_colour_manual(values = c("red", "forestgreen"))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


编辑

现在我们有了一个更具体的例子,我可以更清楚地看到问题。有一些变通方法,例如使用ggnewscale或手工制作的解决方案,例如 Ian Campbell 的完整示例。就个人而言,我只是注意到您还没有使用填充比例,这在我看来非常好:

在此处输入图片说明