代码之家  ›  专栏  ›  技术社区  ›  rez

使用geom\U文本在geom\U点中添加过滤的行名作为标签(数据集长度错误)

  •  2
  • rez  · 技术社区  · 2 年前

    我有一个数据集,我想将特定的标签(在本例中是行名)添加到我的ggplot图中。然而,当我使用filter时,控制台上会显示一个关于数据帧长度的错误。

    require("ggrepel")
    require("tidyerse")
    
    x <- sample(x = 1:20, size = 30, replace = T)
    y <- sample(x = 1:20, size = 30, replace = T)
    df <- data.frame(x,y)
    
    df %>% ggplot(aes(x=x,y=y))+
      geom_point()+
      geom_text_repel(aes(label = rownames(df)))
    
    df %>% ggplot(aes(x=x,y=y))+
      geom_point()+
      geom_text_repel(data = df %>% filter(x>10), 
                        aes(label = rownames(df)))
    

    中出错 check_aesthetics() :

    1 回复  |  直到 2 年前
        1
  •  3
  •   AndrewGB    2 年前

    df 对于行名,则仍将返回所有行名。因此,您还需要在 rownames() aes(label = rownames(df %>% filter(x > 10))) ).

    library(tidyverse)
    
    df %>%
      ggplot(aes(x = x, y = y)) +
      geom_point() +
      geom_text_repel(data = df %>% filter(x > 10),
                      aes(label = rownames(df %>% filter(x > 10))))
    

    enter image description here

        2
  •  2
  •   TarJae    2 年前

    另一种方法可以是:

    my_label 以x>10 不需要在ggplot内子集:

    library(tidyverse)
    
    df %>% 
      group_by(group_id = x > 10) %>% 
      mutate(my_label = ifelse(group_id == TRUE, as.character(row_number()), "")) %>% 
      ggplot(aes(x=x,y=y))+
      geom_point()+
      geom_text_repel(aes(label=my_label))
    

    enter image description here