ggplot:以正确的值标记 geom_smooth / stat_smooth 值

jza*_*dra 2 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)
Run Code Online (Sandbox Code Playgroud)

未对齐的标签

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

Bri*_*ian 5

我不确定这是否真的更优雅,但这一切都在一根管子里。我手边没有“排斥”版本,但想法是一样的。

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)}
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

您需要在最终 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)}
Run Code Online (Sandbox Code Playgroud)