【问题标题】:ggplot: labelling geom_smooth / stat_smooth values at correct valueggplot:将 geom_smooth / stat_smooth 值标记为正确值
【发布时间】:2017-08-07 23:14:23
【问题描述】:

我试图让标签与平滑线的值对齐。虽然我看到的其他答案建议创建一个预测值的数据列,但我正在寻找一种更清洁的替代方案,它使用已经为 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)

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

【问题讨论】:

    标签: r ggplot2 ggrepel


    【解决方案1】:

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

    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)}
    

    您需要在最终 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)}
    

    【讨论】:

      猜你喜欢
      • 2020-10-27
      • 1970-01-01
      • 2021-11-12
      • 1970-01-01
      • 1970-01-01
      • 2018-01-01
      • 2018-05-24
      • 2020-04-03
      • 2020-09-30
      相关资源
      最近更新 更多