使用 par 函数绘制基于数据组的多个图形

Plotting multiple graphs based on data groups using par function

我需要在 R 中绘制 4 个图,x 轴为位置,y 轴为弹珠数。数据中有四组,根据SetBlock是唯一的。

现在,我正在根据Block对每个数据进行子设置并绘制它。之后,我使用 par() 函数将它们全部绘制在一起。

有没有一种简单的方法可以在不手动对数据进行子集化的情况下绘制数据?

  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

您可以使用 ggplot2::facet_wrap():

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

数据:

 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")  

实际使用 par 和基础 plot

op <- par(mfrow=c(2, 2))
by(d, d$Block, function(b) plot(Marbles ~ Position, b, ylim=c(0, max(d$Marbles)), 
                                main=unique(b$Block)))
par(op)


数据

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