This is a test version of Biostars. For the public version, visit https://www.biostars.org.
How to add Seurat Object name in DimPlot title?

Hi,

I have been trying to add Seurat object name in the DimPlot Title without any success. Could you please help me how it can be done? My code-

 x=c(seuratobject1, seuratobject2)

pdf("plots.pdf", onefile = TRUE)

for (i in x){

  b02 <- RunPCA(i, assay = "SCT", verbose = FALSE)

  b02 <- FindNeighbors(b02, reduction = "pca", dims = 1:30)

  b02 <- FindClusters(b02, verbose = FALSE)

  b02 <- RunUMAP(b02, reduction = "pca", dims = 1:30)

  myTitle <- deparse(substitute(j))[1]

  p=print(DimPlot(b02, reduction = "umap", label = TRUE)+ggtitle(myTitle)+ SpatialDimPlot(b02, label = TRUE, label.size = 3))

}

dev.off()
seurat r

1 answer

j is not defined anywhere in your code, so your command will always return the letter 'j' as the title. you probably wanted i instead to return the symbol name.

In general when you want to have access to element names in a loop it's better to name the elements and loop through the element names. Your code would instead look something like this.

x <- list(
  "seuratobject1"=seuratobject1,
  "seuratobject2"=seuratobject2)

pdf("plots.pdf", onefile = TRUE)

for (i in names(x)){

  b02 <- RunPCA(x[[i]], assay = "SCT", verbose = FALSE)

  b02 <- FindNeighbors(b02, reduction = "pca", dims = 1:30)

  b02 <- FindClusters(b02, verbose = FALSE)

  b02 <- RunUMAP(b02, reduction = "pca", dims = 1:30)

  print(DimPlot(b02, reduction = "umap", label = TRUE)+ggtitle(i)+ SpatialDimPlot(b02, label = TRUE, label.size = 3))

}

dev.off()

Thank you! Sorry j was typo in the code it should have been i. Instead of x[i], I used x[[i]] and it works perfectly. I was able to print Seurat object name in ggtitle using following code.

x <- list( "seuratobject1"=seuratobject1, "seuratobject2"=seuratobject2)

pdf("plots.pdf", onefile = TRUE)

for (i in names(x)){

  b02 <- RunPCA(x[[i]], assay = "SCT", verbose = FALSE)

  b02 <- FindNeighbors(b02, reduction = "pca", dims = 1:30)

  b02 <- FindClusters(b02, verbose = FALSE)

  b02 <- RunUMAP(b02, reduction = "pca", dims = 1:30)

  print(DimPlot(b02, reduction = "umap", label = TRUE)+ggtitle(i)+ SpatialDimPlot(b02, label = TRUE, label.size = 3))

}

dev.off()

Log in to answer this question.