0
$\begingroup$

I made this wrapper for DimPlot:

highlight_gene_expression <- function(seurat, gene_counts, colors = NULL, cells = NULL){
  Idents(seurat) <- 'cell_type'
  p <- DimPlot(
    seurat,
    raster = FALSE,
    shuffle = TRUE,
    reduction = "umap",
    pt.size = 0.01,
    cells = cells,
    cols = colors,
  )
  p <- p + guides(color = guide_legend(override.aes = list(size = 4), ncol = 1))

  if (!is.null(cells)) { gene_counts <- gene_counts[cells,] }
  expression_level <- {gene_counts |> rowSums()} / {gene_counts |> rowSums() |> max()}
  p[[1]]$layers[[1]]$aes_params$alpha <- expression_level
  p
}

It takes a Seurat object and a dataframe of gene expression levels. It returns a UMAP with the transparency (alpha) of each point determined by the gene expression level:

highlight_gene_expression(
  seurat, # a seurat object
  trgd_counts, # A dataframe of gene expression levels.  Not important to understand for this question.
  cells = trgd_cells, # A vector of cell barcodes
  colors = colors # c("Erythrocytes"="#556b2f", "HSPCs"="#483d8b", "Proliferating T Cells"="#3cb371", ...)
)

umap with identity colors

Taking it one step further, I highlight the desired cells instead of just coloring them:

highlight_gene_expression <- function(seurat, gene_counts, cells = rownames(seurat@meta.data), colors = NULL){
  Idents(seurat) <- 'cell_type'
  p <- DimPlot(
    seurat,
    raster = FALSE,
    shuffle = TRUE,
    reduction = "umap",
    cols.highlight = colors,
    pt.size = 0.01,
    sizes.highlight = 0.01,
    cells.highlight = seurat@meta.data[cells,] %>% split(.$cell_type) |> lapply(rownames),
  )
  p <- p + guides(color = guide_legend(override.aes = list(size = 4), ncol = 1))

  expression_level <- {gene_counts |> rowSums()} / {gene_counts |> rowSums() |> max()}
  p[[1]]$layers[[1]]$aes_params$alpha <- expression_level
  p
}

This produces a similar plot, but with unhighlighted points in gray. I think it looks quite nice:

# Same params as before
highlight_gene_expression(seurat, trgd_counts, cells = trgd_cells, colors = colors)

highlighted umap with sequential colors

The problem is that the colors are in the wrong places. Dimplot accepts my color vector, but it applies it sequentially when used for highlighting. This means colors are no longer tied to a specific cluster as they were in the previous example. A cluster will have a different color now depending on which ones are actually highlighted.

This is not a bug. Rather, it is expected behavior if you look at the documentation for DimPlot. The cols param corresponds to an identity class. cols.highlight does not. But I want it to. How can I make cols.highlight explicitly define colors for each cluster?

$\endgroup$

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.