按r中基准图中一个变量的级别排列多个图

按r中基准图中一个变量的级别排列多个图,r,graphics,plot,base,par,R,Graphics,Plot,Base,Par,这是我的数据和图表 nmar <- seq (1, 100, 5) position= rep(nmar, 5) n = length (nmar ) chr = rep(1:5, each = n ) mapdata <- data.frame (chr, position, snpname = paste("SNP-", 1:length (position), sep = "")) mapdata chr.lab = 1 ; mbar.col = "blue" lay

这是我的数据和图表

nmar <- seq (1, 100, 5)
position= rep(nmar, 5)
n = length (nmar )
chr = rep(1:5, each = n )

mapdata <- data.frame (chr, position, 
 snpname = paste("SNP-", 1:length (position), sep = ""))
mapdata


chr.lab = 1 ; mbar.col = "blue"
layout(matrix(c(1,1,2),nc=1)) # works for two but I need to extend it to 
       n (which is level of chr = 5)

# plot level 1
mapdata1 <- mapdata[mapdata$chr == 1,]
m <- par()$mar
m[1] <- m[3] <- 0
par(mar=m)
# Set the limits of the  plot
plot(mapdata1$position,mapdata1$position-mapdata1$position, type="n",
   axes=FALSE, 
xlab="", ylab="Chromsome", yaxt="n" )

polygon(
  c(0,max(mapdata1$position + 0.08 * max(mapdata1$position)),max(mapdata1$position)+
     0.08 * max(mapdata1$position),0),
  .2*c(-0.3,-0.3,0.3,0.3),
  col= mbar.col
)
segments(mapdata1$position, -.3, mapdata1$position, .3 )
text(mapdata1$position, -.7, mapdata1$snpname, srt = 90, cex.lab = chr.lab)
text(mapdata1$position,  .7, mapdata1$position,cex.lab = chr.lab )
text(0, labels = c("Chr 2"))

nmar
ggplot
绝对是一种方法。但如果您确实想坚持使用base
plot
,则此函数将起作用:

plot.as.stack= function(mapdata1, mbar.col = "blue"){
    # mapdata1 <- mapdata[mapdata$chr == chr,]
    m <- par()$mar
    m[1] <- m[3] <- 0
    par(mar=m)
    # Set the limits of the  plot
    plot(mapdata1$position,mapdata1$position-mapdata1$position, type="n",
       axes=FALSE, 
    xlab="", ylab="Chromsome", yaxt="n" )

    polygon(
      c(0,max(mapdata1$position + 0.08 * max(mapdata1$position)),max(mapdata1$position)+
         0.08 * max(mapdata1$position),0),
      .2*c(-0.3,-0.3,0.3,0.3),
      col= mbar.col
    )
    segments(mapdata1$position, -.3, mapdata1$position, .3 )
    text(mapdata1$position, -.7, mapdata1$snpname, srt = 90, cex.lab = chr.lab)
    text(mapdata1$position,  .7, mapdata1$position,cex.lab = chr.lab )
    text(0, labels = paste("Chr",unique(mapdata1$chr)))
}

# Example Run.
par(mfrow=c(length(unique(mapdata$chr)),1))
x=by(mapdata,factor(mapdata$chr),plot.as.stack) # Assigned to x to prevent output
par(mfrow=c(1,1))
然后使用chr值运行函数:

par(mfrow=c(5,1))
sapply(1:5,plot.as.stack)
par(mfrow=c(1,1))

有什么特别的理由要坚持基本原则吗?ggplot2和lattice为创建此类复合图提供了简单的解决方案。查看这些链接,了解许多示例。我同意ggplot2和lattice更好,但我觉得它们很难操作,不是吗?一旦掌握了诀窍,我发现ggplot2很容易使用。在我看来,切换到ggplot2或lattice是绝对值得的,尽管在使用了这两种工具之后,我更喜欢ggplot2。
plot.as.stack = function(chr){
    mapdata1 <- mapdata[mapdata$chr == chr,]
    ...
}
par(mfrow=c(5,1))
sapply(1:5,plot.as.stack)
par(mfrow=c(1,1))