Search code examples
rggplot2scatter-plotggpubr

Selective point labeling with ggpubr::ggscatter()


Currently all the points are labeled. If I want to label only specific points in this diagram, but not all the points, how can I accomplish this? I want to remove all the other labels, but keep the labels for 'Herens', 'Payerne', 'Orbe', "Val de Ruz", "Lavaux"

data("swiss")
head(swiss)
library(magrittr)
library(dplyr)
library(ggpubr)
# Cmpute MDS
mds <- swiss %>%
  dist() %>%          
  cmdscale() %>%
  as_tibble()
colnames(mds) <- c("Dim.1", "Dim.2")
# Plot MDS
ggscatter(mds, x = "Dim.1", y = "Dim.2", 
          label = rownames(swiss),
          size = 1,
          repel = TRUE)

Current output

enter image description here

Source code taken from http://www.sthda.com/english/articles/31-principal-component-methods-in-r-practical-guide/122-multidimensional-scaling-essentials-algorithms-and-r-code/


Solution

  • One option would be to add the labels "manually" using ggrepel::geom_text_repel. This allows to filter for your desired categories using an if_else:

    library(dplyr, warn.conflicts = FALSE)
    library(ggpubr)
    #> Loading required package: ggplot2
    library(ggrepel)
    
    # Cmpute MDS
    mds <- swiss %>%
      dist() %>%
      cmdscale() %>%
      as_tibble()
    #> Warning: The `x` argument of `as_tibble.matrix()` must have unique column names if
    #> `.name_repair` is omitted as of tibble 2.0.0.
    #> ℹ Using compatibility `.name_repair`.
    colnames(mds) <- c("Dim.1", "Dim.2")
    
    mds$label <- rownames(swiss)
    
    # Plot MDS
    ggscatter(mds,
      x = "Dim.1", y = "Dim.2",
      size = 1
    ) +
      ggrepel::geom_text_repel(
        aes(label = if_else(label %in% c('Herens', 'Payerne', 'Orbe', "Val de Ruz", "Lavaux"), label, ""))
      )