# Using ggplot2 with slingshot

#### Hector Roux de Bézieux and Kelly Street

#### 31/03/2021

# Introduction

`Slingshot`(Street et al. 2018) is a popular and powerful trajectory inference tool, available from bioconductor. While it only provides default plotting functions in base R, the package also offer conversion functions that can be used to generate plots with `ggplot2`(Wickham 2016).

We will assume that you are both familiar with `slingshot` and `ggplot2`. Otherwise, please refere to the respective packages’ vignettes.

# Running slingshots

We run `slingshot` on the provided example

    # Running slinghsot
    suppressPackageStartupMessages(library(slingshot))
    data("slingshotExample")
    rd <- slingshotExample$rd
    colnames(rd) <- c("Dim1", "Dim2")
    cl <- slingshotExample$cl
    df <- data.frame(rd, "cl" = as.character(cl))
    sds <- slingshot(rd, cl)

We can then visualize the samples in reduced dimension.

    suppressPackageStartupMessages(library(ggplot2))
    suppressPackageStartupMessages(library(dplyr))
    # Plotting the results
    p <- ggplot(df, aes(x = Dim1, y = Dim2)) +
      geom_point(aes(fill = cl), col = "grey70", shape = 21) +
      theme_classic()
    p

# Adding the curves to a ggplot2 object

Then, we can add the curves. We can extract the needed information using the accessory functions. This can be turned into tidy data.frames that interact nicely with `ggplot2` by setting the `as.df` argument to `TRUE`.

    curves <- slingCurves(sds, as.df = TRUE)
    p + geom_path(data = curves %>% arrange(Order),
                  aes(group = Lineage))

We can do all the usual ggplot2 operations

    p + geom_path(data = curves %>% arrange(Order),
                  aes(group = Lineage), size = 1.5)

    ## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
    ## ℹ Please use `linewidth` instead.
    ## This warning is displayed once every 8 hours.
    ## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
    ## generated.

    p + geom_path(data = curves %>% arrange(Order),
                  aes(group = Lineage, col = as.character(Lineage)), size = 1.5)

# Showing the minimum spanning tree

`slingshot` relies on a minimum spanning tree to build the lineages. We can extract the information via:

    mst <- slingMST(sds, as.df = TRUE)

We can then plot the nodes of the graph

    p + geom_point(data = mst, size = 4)

And then add the edges

    p + geom_point(data = mst, size = 4) +
      geom_path(data = mst %>% arrange(Order), aes(group = Lineage), size = 2)

# Building on existing tools

`ggplot2` objects are very versatile. It is therefore quite easy to add the slingshot information to the output of a function that returns such an object. Here we demonstrate with the `plotReducedDim` function from the `scater` package(McCarthy et al. 2017).

    suppressPackageStartupMessages(library(scater))
    suppressPackageStartupMessages(library(SingleCellExperiment))
    sce <- SingleCellExperiment(assays = list(counts = t(rd)),
                                colData = df)
    reducedDim(sce, "Dim") <- rd
    p <- plotReducedDim(sce, dimred = "Dim", colour_by = "cl")
    p

Then, it is quite straightforward to add the curves. We just need to rename the components as X and Y

    curves <- slingCurves(sds, as.df = TRUE) %>%
      dplyr::rename("X" = "Dim1", "Y" = "Dim2")
    p + geom_path(data = curves %>% arrange(Order),
                  aes(group = Lineage))

Similarly for the MST:

    mst <- slingMST(sds, as.df = TRUE) %>%
      dplyr::rename("X" = "Dim1", "Y" = "Dim2")
    p + geom_point(data = mst, size = 4) +
      geom_path(data = mst %>% arrange(Order), aes(group = Lineage), size = 2)

If you have trouble figuring out how to adapt this to other functions, feel free to open an issue on the traviz repo.

# Session Info

    sessionInfo()

    ## R version 4.5.0 (2025-04-11 ucrt)
    ## Platform: x86_64-w64-mingw32/x64
    ## Running under: Windows Server 2022 x64 (build 20348)
    ##
    ## Matrix products: default
    ##   LAPACK version 3.12.1
    ##
    ## locale:
    ## [1] LC_COLLATE=C
    ## [2] LC_CTYPE=English_United States.utf8
    ## [3] LC_MONETARY=English_United States.utf8
    ## [4] LC_NUMERIC=C
    ## [5] LC_TIME=English_United States.utf8
    ##
    ## time zone: America/New_York
    ## tzcode source: internal
    ##
    ## attached base packages:
    ## [1] stats4    stats     graphics  grDevices utils     datasets  methods
    ## [8] base
    ##
    ## other attached packages:
    ##  [1] scater_1.37.0               scuttle_1.19.0
    ##  [3] dplyr_1.1.4                 ggplot2_3.5.2
    ##  [5] slingshot_2.17.0            TrajectoryUtils_1.17.0
    ##  [7] SingleCellExperiment_1.31.0 SummarizedExperiment_1.39.0
    ##  [9] Biobase_2.69.0              GenomicRanges_1.61.0
    ## [11] GenomeInfoDb_1.45.4         IRanges_2.43.0
    ## [13] S4Vectors_0.47.0            BiocGenerics_0.55.0
    ## [15] generics_0.1.4              MatrixGenerics_1.21.0
    ## [17] matrixStats_1.5.0           princurve_2.1.6
    ## [19] knitr_1.50
    ##
    ## loaded via a namespace (and not attached):
    ##  [1] beeswarm_0.4.0            gtable_0.3.6
    ##  [3] xfun_0.52                 bslib_0.9.0
    ##  [5] ggrepel_0.9.6             lattice_0.22-7
    ##  [7] vctrs_0.6.5               tools_4.5.0
    ##  [9] parallel_4.5.0            tibble_3.2.1
    ## [11] pkgconfig_2.0.3           BiocNeighbors_2.3.1
    ## [13] Matrix_1.7-3              RColorBrewer_1.1-3
    ## [15] sparseMatrixStats_1.21.0  lifecycle_1.0.4
    ## [17] compiler_4.5.0            farver_2.1.2
    ## [19] codetools_0.2-20          vipor_0.4.7
    ## [21] htmltools_0.5.8.1         sass_0.4.10
    ## [23] yaml_2.3.10               pillar_1.10.2
    ## [25] crayon_1.5.3              jquerylib_0.1.4
    ## [27] BiocParallel_1.43.3       DelayedArray_0.35.1
    ## [29] cachem_1.1.0              viridis_0.6.5
    ## [31] abind_1.4-8               rsvd_1.0.5
    ## [33] tidyselect_1.2.1          digest_0.6.37
    ## [35] BiocSingular_1.25.0       labeling_0.4.3
    ## [37] cowplot_1.1.3             fastmap_1.2.0
    ## [39] grid_4.5.0                cli_3.6.5
    ## [41] SparseArray_1.9.0         magrittr_2.0.3
    ## [43] S4Arrays_1.9.1            dichromat_2.0-0.1
    ## [45] withr_3.0.2               DelayedMatrixStats_1.31.0
    ## [47] scales_1.4.0              UCSC.utils_1.5.0
    ## [49] ggbeeswarm_0.7.2          rmarkdown_2.29
    ## [51] XVector_0.49.0            httr_1.4.7
    ## [53] igraph_2.1.4              gridExtra_2.3
    ## [55] ScaledMatrix_1.17.0       beachmat_2.25.1
    ## [57] evaluate_1.0.3            viridisLite_0.4.2
    ## [59] irlba_2.3.5.1             rlang_1.1.6
    ## [61] Rcpp_1.0.14               glue_1.8.0
    ## [63] jsonlite_2.0.0            R6_2.6.1

# References

McCarthy, Davis J., Kieran R. Campbell, Aaron T. L. Lun, and Quin F. Willis. 2017. “Scater: Pre-Processing, Quality Control, Normalisation and Visualisation of Single-Cell RNA-Seq Data in R.” Bioinformatics 33 (8): 1179–86. https://doi.org/10.1093/bioinformatics/btw777.

Street, Kelly, Davide Risso, Russell B. Fletcher, Diya Das, John Ngai, Nir Yosef, Elizabeth Purdom, and Sandrine Dudoit. 2018. “Slingshot: cell lineage and pseudotime inference for single-cell transcriptomics.” BMC Genomics 19 (1): 477. https://doi.org/10.1186/s12864-018-4772-0.

Wickham, Hadley. 2016. Ggplot2: Elegant Graphics for Data Analysis. Springer-Verlag New York. https://ggplot2.tidyverse.org.