0

Thank you for this wonderful community. I am trying to create a loop to make lots of graphs. However, only the last graph is being shown.

Here is my dataset. I am essentially subsetting by gene and then trying to create graphs.

enter image description here

Here is my code.

data_before_heart <- subset(data_before, Organ == 0)
uniq <- unique(unlist(data_before_heart$Gene))
for (i in 1:length(uniq)){
  data_1 <- subset(data_before_heart, Gene == uniq[i])
  print(ggplot(data_1, aes(x=Drug, y=Expression)) +
    geom_bar(stat="identity"))
}

Unfortunately this only generates the last graph. (there are 6 genes from 0, 1, 2, 3, 4, 5)

Z.Lin
  • 28,055
  • 6
  • 54
  • 94
GJK
  • 23
  • 3
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. Don't share data in a image because we can't copy/paste that into R. Where do you want all these graphs to go exactly? The graphics windows only draws the last request. Each new `print()` erases what was there before. – MrFlick Jun 29 '20 at 22:53
  • 1
    Possible duplicate: https://stackoverflow.com/questions/52436487/show-multiple-plots-from-ggplot-on-one-page-in-r or https://stackoverflow.com/questions/9315611/grid-of-multiple-ggplot2-plots-which-have-been-made-in-a-for-loop – MrFlick Jun 29 '20 at 22:53
  • If using RStudio, remember to shuffle through all plots with arrows. Only last plot shows in viewer. – Parfait Jun 30 '20 at 00:46
  • You could export your loop onto a format that can compile multiple graphical instances, such as pdf. – Adam Quek Jun 30 '20 at 05:25

1 Answers1

1

You code works fine for me with 'fake' data and generates the expected number of bar plots without any issues:

library(ggplot2)
library(dplyr)

data_before_heart <- data.frame(
  Gene = as.vector(sapply(seq(1:10), function(x) x*rep(1, 5))) - 1,
  Drug =  c(0, seq(1:50) %% 5)[1:50],
  Expression = runif(n = 50, min = 0, max = 1),
  stringsAsFactors = FALSE
)
   
#data_before_heart <- subset(data_before, Organ == 0)
uniq <- unique(unlist(data_before_heart$Gene))
for (i in 1:length(uniq)){
  data_1 <- subset(data_before_heart, Gene == uniq[i])
  print(ggplot(data_1, aes(x=Drug, y=Expression)) +
          geom_bar(stat="identity"))
}

Perhaps your data set has issues? Are there any error messages? facet_wrap provides an elegant alternative:

data_before_heart %>%
  ggplot(aes(x = Drug, y = Expression)) +
  geom_bar(stat = "identity") +
  facet_wrap(~ Gene, nrow = 5, ncol = 2, scales = "fixed")

enter image description here

Paul van Oppen
  • 1,443
  • 1
  • 9
  • 18