Reputation: 71
Hi I am writing an R function to generate a fluctuation plot using ggplot2
fluctuation <- function(filename)
x=read.table(filename,sep=",")
mydata=melt(x)$value
mydata=matrix(mydata,ncol=4, byrow=T)
colnames(mydata) <-c("AA", "AB", "BB","no.call")
rownames(mydata) <-c("AA", "AB", "BB", "no.call")
data.melt=melt(mydata)
names(data.melt)<-c("pgm", "truth", "value")
p <- ggfluctuation(data.melt)+ xlab("Truth") + ylab("Pgmsnp")
p2 <- p + geom_text(aes(label=data.melt$value),colour="black", main="whole-exome capture")
return (p2)
When I run this code:
fluctuation("file.csv")
I get the following error:
Error in eval(expr, envir, enclos) : object 'data.melt' not found
However, if I return p, its fine. So there is some issue with
geom_text(aes(label=data.melt$value),colour="black", main="whole-exome capture")
But I can't figure it out. I'm still a bit of a ggplot2 newbie. I googled around and found similar questions, but I can't seem to fix my instance. Can someone help point me in the right direction?
Upvotes: 1
Views: 209
Reputation: 71
Well, there is something I don't understand about how R handles functions. If I explicitly glob all my input files and then make the plots by iterating through the list of file inputs I want to make a plot for, it works.
library("ggplot2")
library("reshape2")
files <- dir(getwd(), pattern = "*.csv", full.names = FALSE)
for (i in 1:length(files)) {
x=read.table(files[i],sep=",")
mydata=melt(x)$value
mydata=matrix(mydata,ncol=4, byrow=T)
colnames(mydata) <-c("AA", "AB", "BB","no.call")
rownames(mydata) <-c("AA", "AB", "BB", "no.call")
data.melt=melt(mydata)
names(data.melt)<-c("pgm", "truth", "value")
plotname <- paste(files[i], "png", sep=".")
p <- ggfluctuation(data.melt) + geom_text(aes(label=data.melt$value)) +xlab("Truth") + ylab("Pgmsnp") + theme(axis.text.x= element_text(size=rel(1.5))) + theme(axis.text.y= element_text(size=rel(1.5))) + theme(axis.title.x = element_text(size = rel(1.5))) + theme(axis.title.y= element_text(size = rel(1.5))) + opts(title = files[i]) + theme(plot.title = element_text(size = rel(.95)))
ggsave(p, file=plotname)
}
Upvotes: 0
Reputation: 9037
I'm not so familiar with the operation of `ggfluctuation()
, but if it's similar to other ggplot functions, you should change it to
p <- ggfluctuation(data.melt)+ xlab("Truth") + ylab("Pgmsnp")
p2 <- p + geom_text(aes(label=value),colour="black", main="whole-exome capture")
ggplot layers inherit the data frame from the original ggplot()
, or in this case, ggfluctuation()
layer. aes()
looks to the data frame it's inheriting when it maps variables, so in this case, only use aes(label=value)
.
Upvotes: 1