I need to plot a gene of interest in only fibroblast cells, however, when I use ImageDimPlot, it keeps showing the expression of the gene in all tissue, although I subsetted the data to only fibroblast.
I know that I have x and y coordinates of the genes in each cell and also x and y coordinates of the cells, however, they are different and the only way I might be able to plot what I am looking for is with defining a threshold for the coordinates of the gene and the cells, however, it won't be visually accurate enough.
I have tried this:
# cell identities: set based on the "subset" metadata.
Idents(nano.obj_all) <- nano.obj_all$subset
# Create a new metadata column 'plot_group' with two levels:
# "Epithelial" for cells where subset equals "epi", and "Other" for all other cells.
nano.obj_all$plot_group <- ifelse(nano.obj_all$subset == "epi", "Epithelial", "Other")
# Define the cells to plot based on the desired identities.
cells_to_plot <- WhichCells(nano.obj_all, idents = c("epi", "stroma", "myeloids", "tcells", "plasmas"))
# Loop in each fov, create an ImageDimPlot and use the custom group,
# Ensure that cell identities are set based on the "subset" metadata.
Idents(nano.obj_all) <- nano.obj_all$subset
# Create a new metadata column 'plot_group' with two levels:
# "Epithelial" for cells where subset equals "epi", and "Other" for all other cells.
nano.obj_all$plot_group <- ifelse(nano.obj_all$subset == "epi", "Epithelial", "Other")
# Force the factor levels to match exactly
nano.obj_all$plot_group <- factor(nano.obj_all$plot_group, levels = c("Epithelial", "Other"))
# Define the cells to plot based on the desired identities.
cells_to_plot <- WhichCells(nano.obj_all, idents = c("epi", "stroma", "myeloids", "tcells", "plasmas"))
# Define the fields of view (fovs).
fovs <- c("Hia", "Hib", "Hic", "Cia", "Cib", "Cic", "Uia", "Uib", "Uic")
# Loop in each fov, create an ImageDimPlot using the custom group, and save the plot as a PNG file.
for (f in fovs) {
p <- ImageDimPlot(nano.obj_all,
fov = f,
cells = cells_to_plot,
molecules = "ABL1",
group.by = "plot_group", # use the new group column for coloring
size = 0.6,
cols = c("Epithelial" = "#4A82F7", "Other" = "#F0B041"), # assign colors manually
) + labs(title = f)
ggsave(filename = paste0("ImageDimPlot_CellType_", f, ".png"),
plot = p,
width = 12,
height = 12,
dpi = 350)
cat("Saved plot for fov:", f, "\n")
}