Search code examples
rplotsubsetpar

Plotting multiple graphs based on data groups using par function


I need to plot 4 plots in R, with position on the x-axis and and number of marbles on the y-axis. There are four groups in the data, and are unique according to the Set and Block.

Right now, I am sub-setting each data according to Block and plotting it. After which I use the par() function to plot them all together.

Is there an easy way to plot the data without subsetting them manually?

  Set Size    Position  Marbles Block
   1   Small  1         8        1
   1   Small  2         81       1
   1   Small  3         3        1
   1   Small  4         4        1
   4   Small  1         8        1
   4   Small  2         81       1
   4   Small  3         3        1
   4   Small  4         4        1
   4   Small  1         14       2
   6   Small  2         11       2
   6   Small  3         12       2
   6   Small  4         25       2
   1   Small  1         8        3
   1   Small  2         81       3
   1   Small  3         3        3
   1   Small  4         4        3
   6   Small  1         14       4
   6   Small  2         11       4
   6   Small  3         12       4
   6   Small  4         25       4

Solution

  • You can use ggplot2::facet_wrap():

    library(ggplot2)
    ggplot(data = dat, aes(x = Position, y = Marbles)) + 
           geom_point() + facet_wrap(~Block)
    

    enter image description here

    Data:

     dat <- structure(list(Set = c(1L, 1L, 1L, 1L, 6L, 6L, 6L, 6L, 1L, 1L,                 
         1L, 1L, 6L, 6L, 6L, 6L), Size = structure(c(1L, 1L, 1L, 1L, 1L,                   
         1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "Small", class = "factor"), 
             Position = c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L,                      
             4L, 1L, 2L, 3L, 4L), Marbles = c(8L, 81L, 3L, 4L, 14L, 11L,                   
             12L, 25L, 8L, 81L, 3L, 4L, 14L, 11L, 12L, 25L), Block = c(1L,                 
             1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L                    
             )), .Names = c("Set", "Size", "Position", "Marbles", "Block"                  
         ), row.names = c(NA, 16L), class = "data.frame")