将geom_text添加到ggfluctuation

时间:2013-06-07 04:25:03

标签: r ggplot2

您好我正在编写一个R函数来生成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)

当我运行此代码时:

fluctuation("file.csv")

我收到以下错误:

Error in eval(expr, envir, enclos) : object 'data.melt' not found

但是,如果我退回p,那很好。

存在一些问题
geom_text(aes(label=data.melt$value),colour="black", main="whole-exome capture")

但我无法弄明白。我还是一个ggplot2新手。我用Google搜索并发现了类似的问题,但我似乎无法修复我的实例。有人能指点我正确的方向吗?

2 个答案:

答案 0 :(得分:1)

我对`ggfluctuation()的操作并不熟悉,但如果它与其他ggplot函数类似,则应将其更改为

p <- ggfluctuation(data.melt)+ xlab("Truth") + ylab("Pgmsnp") 
p2 <- p  + geom_text(aes(label=value),colour="black", main="whole-exome capture")

ggplot图层从原始ggplot()继承数据框,或者在此情况下继承ggfluctuation()图层。 aes()查看映射变量时继承的数据框,因此在这种情况下,只使用aes(label=value)

答案 1 :(得分:0)

嗯,我不了解R如何处理功能。如果我显式地对我的所有输入文件进行全局处理,然后通过遍历我想要绘制的文件输入列表来制作绘图,则它可以正常工作。

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)



}
相关问题