0

Hopefully you could help me out with the following. I have a large dataset from which I will build 56 plots using the following function

markers <- unique(patient_flow$marker_id)
marker_data <- ap_fcm_raw$markerdata

library(ggplot2)

for (i in markers){
p <- ggplot(data = subset(patient_flow, marker_id == i))+
    aes(x = as.numeric(pbd_cat), y = result, color = study)+
  ggtitle(marker_data$explanation[i])+
  geom_smooth()+
  geom_point()+
      labs(x = "Post Burn day")

ggsave(p, file=paste0("FCM_plots/plot_", i, ".png"))
}

The code above works. Data is subsetted based on markers and graphs are build. For the ggtitle I get the marker-id (which is only a number). I want to replace this using the "explanation" column provided in the marker_data dataframe (see example below)

structure(list(marker_id = c("events_001", "ptot_002", "events_003", 
"ppar_004", "ptot_005", "events_006"), name = c("all_e", "all_e_t", 
"cell_e", "cell_p", "cell_t", "single_e"), cell_type = c("events", 
"events", "cells", "cells", "cells", "singlets"), gate = c("All Events\r\nEvents\r\n\r\n", 
"All Events\r\n%\r\nTotal\r\n\r\n", "Cells\r\nEvents\r\n\r\n", 
"Cells\r\n%\r\nParent\r\n\r\n", "Cells\r\n%\r\nTotal\r\n\r\n", 
"Singlets\r\nEvents\r\n\r\n"), explanation = c("All events in total", 
"Percentage of all total events", "Number of cells", "Percentage of Cells of Parent gate", 
"Percentage of cells of Total events", "Number of single events"
), panel = c("p2", "p2", "p2", "p2", "p2", "p2")), row.names = c(NA, 
-6L), class = c("tbl_df", "tbl", "data.frame"))

However, ggplot builds the graph but the title is "NA"

enter image description here

I also tried to paste using ggtitle(paste(marker_data$explanation[i])), but this also returned with NA. How can I make this work?

stefan
  • 90,330
  • 6
  • 25
  • 51
  • As you are looping over the `marker_id`s try with `marker_data$explanation[marker_data$marker_id %in% i]`. – stefan Jul 19 '23 at 15:42

1 Answers1

0

As suggested I changed the code to

for (i in markers){
p <- ggplot(data = subset(patient_flow, marker_id == i))+
    aes(x = as.numeric(pbd_cat), y = result, color = study)+
  ggtitle(marker_data$explanation[marker_data$marker_id %in% i])+
  geom_smooth()+
  geom_point()+
    theme_classic()+
      labs(x = "Post Burn day")

ggsave(p, file=paste0("FCM_plots/PBD_cat/plot_", i, ".png"))
}

Which worked nicely

enter image description here