Search code examples
rstatisticsbar-chartgplots

How do i put multiple separate charts onto one pdf in r


I am having trouble figuring how to put 6 separate bar plots onto one pdf. This is one of the plots for example (they are all very similar):

    barplot(druhy, ylim = c(0,50), main = "Míváš často chuť na svíčkovou?", col = c("red", "blue", "green", "black", "yellow"))

   legend("topleft", legend = c("ano", "spíše ano", "nevím", "spíše ne", "ne"), fill = c("red", "black", "green", "yellow", "blue"))

And here are the values the chart uses:

  print(druhy)

  ano\r\n        ne\r\n     nevím\r\n spíše ano\r\n  spíše ne\r\n 
        4             1             2             5             3 

I tried this code to put them onto one pdf together, but it doesn't work. I am sure there is something wrong in this code, but i just can not seem to find what excactly.

    pdf('plot.pdf')

  m <- rbind(c(1,2), c(3,4), c(5,6))
  layout(m)
  sapply(seq_along(sp),
   function(x) {
     dd <- sp[[x]]
     m <- t(`rownames<-`(as.matrix(dd[, -(1:2)]), dd[, 1]))
     bp <- barplot(m,ylim=c(0, 0.4),beside=TRUE,col=barcols)
     title(main=names(sp[x]))
     # abline(h=0)
   }
plot(NA,xlim=c(0,1),ylim=c(0,1),ann=FALSE,axes=FALSE)

Is there any better way or how do i fix this code, so the outcome is a pdf with six side by side barplots? I am a beginner, so I apologize if my question is downright stupid.


Solution

  • The end of plotting must be indicated using dev.off(). Here is a simple working example:

    pdf("myOut.pdf")
    for (i in 1:10){
      barplot(iris$Sepal.Length)
    }
    dev.off()