R multiplot - R cookbook错误'美学必须是长度一......“

时间:2014-09-10 12:12:36

标签: r ggplot2

我正在尝试使用R cookbook multiplot函数将两个图表彼此相邻,但我收到以下错误:

  

Aesthetics must either be length one, or the same length as the dataProblems:v.x

有人可以帮忙吗?我的代码如下:

rm(list=ls())
library(ggplot2)
library(grid)

# Multiple plot function
multiplot <- function(..., plotlist=NULL, file, cols=1, layout=NULL) {
  require(grid)

  # Make a list from the ... arguments and plotlist
  plots <- c(list(...), plotlist)

  numPlots = length(plots)

  # If layout is NULL, then use 'cols' to determine layout
  if (is.null(layout)) {
    # Make the panel
    # ncol: Number of columns of plots
    # nrow: Number of rows needed, calculated from # of cols
    layout <- matrix(seq(1, cols * ceiling(numPlots/cols)),
                     ncol = cols, nrow = ceiling(numPlots/cols))
  }

  if (numPlots==1) {
    print(plots[[1]])

  } else {
    # Set up the page
    grid.newpage()
    pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))

    # Make each plot, in the correct location
    for (i in 1:numPlots) {
      # Get the i,j matrix positions of the regions that contain this subplot
      matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE))

      print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
                                          layout.pos.col = matchidx$col))
    }
  }
}

# Define beta binomial function
dbb <- function(x, N, u, v) {
  beta(x+u, N-x+v)/beta(u,v)*(gamma(N+1)/(gamma(x+1)*gamma(N-x+1)))
}

#Prior parameters
a<-1
b<-1

#Data
N1<-100
X<-10

#New sample
N2 <- 100

# Generate prior, likelihood, posterior and posterior predictive distribution
v.theta <- seq(0,1,length=1000) 
v.x <-seq(0,100,length=100) 
v.prior <- dbeta(v.theta,a,b)
v.likelihood <- choose(N1,X)*(v.theta^X)*(1-v.theta)^(N1-X);
v.posterior <- dbeta(v.theta,a+X,b+N1-X)
v.posteriorPred <- dbb(v.x,N2,a+X,b+N1-X)

# Plot as a subplot
p1<-qplot(v.x,v.prior,geom = c("point", "line"))
p2<-qplot(v.x,v.likelihood,geom = c("point", "line"))

multiplot(p1, p2)

1 个答案:

答案 0 :(得分:0)

问题是向量v.x与v.prior的长度不同。现在已经改变了!