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

    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.2.0 RC (2022-04-19 r82224 ucrt)
    ## Platform: x86_64-w64-mingw32/x64 (64-bit)
    ## Running under: Windows Server x64 (build 20348)
    ##
    ## Matrix products: default
    ##
    ## 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
    ##
    ## attached base packages:
    ## [1] stats4    stats     graphics  grDevices utils     datasets  methods
    ## [8] base
    ##
    ## other attached packages:
    ##  [1] scater_1.24.0               scuttle_1.6.0
    ##  [3] dplyr_1.0.8                 ggplot2_3.3.5
    ##  [5] slingshot_2.4.0             TrajectoryUtils_1.4.0
    ##  [7] SingleCellExperiment_1.18.0 SummarizedExperiment_1.26.0
    ##  [9] Biobase_2.56.0              GenomicRanges_1.48.0
    ## [11] GenomeInfoDb_1.32.0         IRanges_2.30.0
    ## [13] S4Vectors_0.34.0            BiocGenerics_0.42.0
    ## [15] MatrixGenerics_1.8.0        matrixStats_0.62.0
    ## [17] princurve_2.1.6             knitr_1.38
    ##
    ## loaded via a namespace (and not attached):
    ##  [1] viridis_0.6.2             sass_0.4.1
    ##  [3] BiocSingular_1.12.0       viridisLite_0.4.0
    ##  [5] jsonlite_1.8.0            DelayedMatrixStats_1.18.0
    ##  [7] bslib_0.3.1               assertthat_0.2.1
    ##  [9] highr_0.9                 GenomeInfoDbData_1.2.8
    ## [11] vipor_0.4.5               ggrepel_0.9.1
    ## [13] yaml_2.3.5                pillar_1.7.0
    ## [15] lattice_0.20-45           glue_1.6.2
    ## [17] beachmat_2.12.0           digest_0.6.29
    ## [19] XVector_0.36.0            colorspace_2.0-3
    ## [21] cowplot_1.1.1             htmltools_0.5.2
    ## [23] Matrix_1.4-1              pkgconfig_2.0.3
    ## [25] zlibbioc_1.42.0           purrr_0.3.4
    ## [27] scales_1.2.0              ScaledMatrix_1.4.0
    ## [29] BiocParallel_1.30.0       tibble_3.1.6
    ## [31] generics_0.1.2            farver_2.1.0
    ## [33] ellipsis_0.3.2            withr_2.5.0
    ## [35] cli_3.3.0                 magrittr_2.0.3
    ## [37] crayon_1.5.1              evaluate_0.15
    ## [39] fansi_1.0.3               beeswarm_0.4.0
    ## [41] tools_4.2.0               lifecycle_1.0.1
    ## [43] stringr_1.4.0             munsell_0.5.0
    ## [45] DelayedArray_0.22.0       irlba_2.3.5
    ## [47] compiler_4.2.0            jquerylib_0.1.4
    ## [49] rsvd_1.0.5                rlang_1.0.2
    ## [51] grid_4.2.0                RCurl_1.98-1.6
    ## [53] BiocNeighbors_1.14.0      igraph_1.3.1
    ## [55] bitops_1.0-7              labeling_0.4.2
    ## [57] rmarkdown_2.14            gtable_0.3.0
    ## [59] DBI_1.1.2                 R6_2.5.1
    ## [61] gridExtra_2.3             fastmap_1.1.0
    ## [63] utf8_1.2.2                stringi_1.7.6
    ## [65] ggbeeswarm_0.6.0          parallel_4.2.0
    ## [67] Rcpp_1.0.8.3              vctrs_0.4.1
    ## [69] tidyselect_1.1.2          xfun_0.30
    ## [71] sparseMatrixStats_1.8.0

# 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.