littleworth
littleworth

Reputation: 5169

How to display label using ggrepel on sorted x and y-axis value

I have the following code:

library(tidyverse)
all_annot_df <- as.tibble(iris)  %>% 
  mutate(Obs = paste0("Obs_", row_number())) %>% 
  select(Obs, Species, Sepal.Length)

signif_thres <- 7.5
all_annot_df["Significant"] <- ifelse((all_annot_df$Sepal.Length > signif_thres),"Signif","NotSignif")
p <- all_annot_df %>% 
  ggplot(aes(reorder(Obs,Sepal.Length), Sepal.Length, colour=Species)) +
  geom_point() +
  theme_bw() + 
  xlab("Observation") +
  theme(axis.text.x=element_blank(),
        axis.ticks.x=element_blank())   + 
  geom_hline(aes(yintercept=signif_thres, colour='red'))


p 

It produces the following plot: enter image description here

As shown in the above figure I'd like to show the label using ggrepel. How can I do it?

Upvotes: 2

Views: 421

Answers (1)

missuse
missuse

Reputation: 19726

library(ggrepel)
library(tidyverse)

Specify the observations you would like annotated

observs = paste0( "Obs_", c(106, 118, 119, 123, 132))

filter the data accordingly

p + 
geom_text_repel(data = all_annot_df %>%
                  filter(Obs %in% observs),
                aes(x = reorder(Obs,Sepal.Length),
                    y = Sepal.Length,
                    label = Obs),
                color= "black")

enter image description here

Upvotes: 2

Related Questions