将直接标签添加到geom_smooth而不是geom_line

问题描述 投票:3回答:2

[我知道这个问题是this one的近似副本,但是那里的解决方案不再起作用(使用method="last.qp"),所以我再次询问。

基本问题是,我想使用directlabels(或等效值)来标记每个组(来自stat_smooth())的平滑均值,而不是实际数据。下面的示例显示了与我所获得的接近的示例,但是标签无法识别分组,甚至无法识别平滑线。相反,我在最后一点得到了标签。我想要的是每条平滑线末端的颜色协调文本,而不是绘图右侧的图例。

这里是一个例子:

library(ggplot2)
library(directlabels)

## Data
set.seed(10)
d <- data.frame(x=seq(1,100,1), y=rnorm(100, 3, 0.5))
d$z <- ifelse(d$y>3,1,0)

## Plot
p <- ggplot(d, aes(x=x, y=y, colour=as.factor(z))) +
  stat_smooth(inherit.aes=T, se=F, span=0.8, show.legend = T) +
  geom_line(colour="grey50") +
  scale_x_continuous(limits=c(0,110)) +
  geom_dl(label="text", method="maxvar.points", inherit.aes=T)
p

绘制此图:enter image description here

r ggplot2 labels ggrepel direct-labels
2个回答
4
投票

基于ggrepel的使用this answer包的解决方案>

library(tidyverse)
library(ggrepel)

set.seed(123456789)

d <- data.frame(x = seq(1, 100, 1), y = rnorm(100, 3, 0.5))
d$z <- ifelse(d$y > 3, 1, 0)

labelInfo <-
  split(d, d$z) %>%
  lapply(function(t) {
    data.frame(
      predAtMax = loess(y ~ x, span = 0.8, data = t) %>%
        predict(newdata = data.frame(x = max(t$x)))
      , max = max(t$x)
    )}) %>%
  bind_rows

labelInfo$label = levels(factor(d$z))
labelInfo

#>   predAtMax max label
#> 1  2.538433  99     0
#> 2  3.293859 100     1

ggplot(d, aes(x = x, y = y, color = factor(z))) + 
  geom_point(shape = 1) +
  geom_line(colour = "grey50") +
  stat_smooth(inherit.aes = TRUE, se = FALSE, span = 0.8, show.legend = TRUE) +
  geom_label_repel(data = labelInfo, 
                   aes(x = max, y = predAtMax, 
                       label = label, 
                       color = label), 
                   nudge_x = 5) +
  theme_classic()
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'

“”

[reprex package(v0.2.0)于2018-06-11创建。


1
投票

您需要告诉geom_dl您想在绘图上显示的内容。下面的代码应仅满足您的需求;

© www.soinside.com 2019 - 2024. All rights reserved.