使用ggplot2绘制函数时出错

时间:2016-10-28 17:34:15

标签: r ggplot2

我绘制堆叠金字塔的代码在终端窗口中运行良好,但在函数内部时会抛出错误。

这是我的代码:

make.pyramid <- function(){
  mydata <- data.frame(factorname=rep(c("first","second"),10), Topic=sort(c(1:10, 1:10)), Distribution=sample(1:200,20))
  mydata <- mydata[order(mydata$factorname,mydata$Topic),]
  topicavg <- c()
  for (row in 1:10) {topicavg[row] <- mydata[row,3]-mydata[row+10,3]}
  topicavg <- c(topicavg,topicavg)
  mydata <- cbind(mydata,topicavg)
  library(ggplot2)
  dist <- ggplot(data=mydata, aes_q(x=substitute(reorder(Topic, topicavg)), y=quote(Distribution), fill=as.name("factorname")))
  dist <- dist + geom_bar(data=subset(mydata,mydata[,1]=="first"), stat="identity")
  dist <- dist + geom_bar(data=subset(mydata,mydata[,1]=="second"), stat="identity", position="identity", mapping=aes(y=-Distribution))
  dist <- dist + scale_y_continuous(labels=abs)
  dist <- dist + xlab("Topics")
  dist <- dist + coord_flip()
  dist <- dist + geom_point(data=subset(mydata,mydata[,1]=="second"), mapping=aes(y=topicavg), shape=4, show.legend = F)
  print(dist)
}

如果我在终端中逐行浏览,我得到一个这样的情节: stacked pyramid chart

但是当在函数中使用时,我收到以下错误:

  

tapply错误(X = X,INDEX = x,FUN = FUN,...):参数必须具有相同的长度

我哪里出错了,我该如何做对?

2 个答案:

答案 0 :(得分:2)

是的,另一个解决方案是创建单独的函数

id_number

答案 1 :(得分:0)

我明白了!我相信我遇到ggplot2的问题会让我不在赛道上。我实际上错误地使用了这个功能。在这个例子中,我需要全局定义我的对象,甚至只是在函数中本地使用它:

make.pyramid <- function(){
  mydata <<- data.frame(factorname=rep(c("first","second"),10), Topic=sort(c(1:10, 1:10)), Distribution=sample(1:200,20))
  mydata <<- mydata[order(mydata$factorname,mydata$Topic),]
  topicavg <<- c()
  for (row in 1:10) {topicavg[row] <- mydata[row,3]-mydata[row+10,3]}
  topicavg <<- c(topicavg,topicavg)
  mydata <<- cbind(mydata,topicavg)
  dist <- ggplot(data=mydata, aes_q(x=substitute(reorder(Topic, topicavg)), y=quote(Distribution), fill=as.name("factorname")))
  dist <- dist + geom_bar(data=subset(mydata,mydata[,1]=="first"), stat="identity")
  dist <- dist + geom_bar(data=subset(mydata,mydata[,1]=="second"), stat="identity", position="identity", mapping=aes(y=-Distribution))
  dist <- dist + scale_y_continuous(labels=abs)
  dist <- dist + xlab("Topics")
  dist <- dist + coord_flip()
  dist <- dist + geom_point(data=subset(mydata,mydata[,1]=="second"), mapping=aes(y=topicavg), shape=4, show.legend = F)
  print(dist)
}