ggplot:将geom_smooth / stat_smooth值标记为正确的值

时间:2017-08-07 23:14:23

标签: r ggplot2 ggrepel

我正在尝试让标签与平滑线上的值对齐。虽然我见过的其他答案建议创建一个预测值的数据列,但我正在寻找一种更清洁的替代方案,它使用已经为ggplot生成的数据。

请参阅下面的示例了解问题:

require(tidyverse)
require(ggrepel)

set.seed(1)
df <- data.frame(x = rep(1:100, 5), y = c(sample(1:20, 100, T), sample(21:40, 100, T), sample(41:60, 100, T), sample(61:80, 100, T), sample(81:100, 100, T)), group = rep(letters[1:5], each = 100))
df <- tbl_df(df)

df %>% 
  ggplot(aes(x = x, y = y, label = group, color = group)) + 
  geom_smooth() +
  guides(color = F) +
  geom_text_repel(data = . %>% filter(x == max(x)), aes(x = x, y = y, label = group), nudge_x = 50)

Misaligned labels

有没有办法在不使用ggplot_build()或其他外部多步骤方法的情况下获得max(x)处的平滑线值?

1 个答案:

答案 0 :(得分:3)

我不确定这是否真的更优雅,但它只是在一个管道中。我没有&#34;击退&#34;版本方便,但想法是一样的。

library(broom)

df %>%
  {ggplot(., aes(x, y, label = group, color = group)) + 
  geom_smooth() + 
  guides(color = F) +
  geom_text(data = group_by(., group) %>% 
                    do(augment(loess(y~x, .))) %>% 
                    filter(x == max(x)),
            aes(x, .fitted), nudge_x = 5)}

enter image description here

你需要在最终的x值上得到黄土更平滑的预测,所以你只需要适应它两次。如果模型拟合很慢,你可以在dplyr链中做一次,更高,只需将输出用于图的其余部分。

df %>%
  group_by(group) %>% 
  do(augment(loess(y~x, .))) %>% 
  {ggplot(., aes(x, y, label = group, color = group)) + 
  geom_smooth() + 
  guides(color = F) +
  geom_text(data = filter(., x == max(x)),
            aes(x, .fitted), nudge_x = 5)}