3

I have a dataset and I want to add specific labels (row names in this case) to my ggplot graph. However, when I use filter, an error regarding length of the data frame shows on the console. I would appreciate if anyone could help me to resolve the issue.

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

Error in check_aesthetics(): ! Aesthetics must be either length 1 or the same as the data (14): label

rez
  • 290
  • 2
  • 12

2 Answers2

3

Since you are using df for rownames, then it would still return all rownames. So, you need to also add you filter statement inside of rownames() (i.e., 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

AndrewGB
  • 16,126
  • 5
  • 18
  • 49
2

An alternative way could be:

Here we define the labels beforehand by adding a column my_label conditional on x> 10. No need to subset within 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

TarJae
  • 72,363
  • 6
  • 19
  • 66