在调用ggplot的函数中传递字符串列名

时间:2015-03-03 19:24:53

标签: r function ggplot2

我正在尝试编写一个带有列名(有空格)的函数,然后将其作为y传递给ggplot函数。我有多个列,我将通过函数中的名称引用。我有一个MWE低于但是。我收到错误:

Error in df$colname : object of type 'closure' is not subsettable

我尝试在stackoverflow上使用其他建议,但我想我不确定是否存在问题,因为我的列名中有空格或者我的代码是否有问题?关于我缺少什么的任何建议?

####code
library(ggplot2)
v1 <- c(1, 2,3,4,5,6)
v2 <- c(13.8, 14.8,12.3,4.5,6,7)
v3 <- c(20,25,30,35,40,45)

df_new <- data.frame("x val"=v1, "y val"=v2, "z val" = v3)
colnames(df_new) <- c("x value","y value","z value")

df_new


testplot <- function(df,colname)
{

    print(rownames(df))
    print(df$colname)
    myplot <- ggplot(data = df, aes(x=rownames(df), y=df$colname,group=1))  
    myplot <- myplot + geom_line() + geom_point() +  theme(panel.grid.major =           element_blank(), panel.grid.minor = element_blank(), 
                                                     panel.background = element_blank(), axis.line = element_line())
myplot

}

testplot(df_new,"x value")
testplot(df_new,"y value")

myplot <- ggplot(data = df_new, aes(x=rownames(df_new), y=df_new$"x value",group=1))  
myplot <- myplot + geom_line() + geom_point() +  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), 
                                                     panel.background = element_blank(), axis.line = element_line())

myplot

0 个答案:

没有答案