繁体   English   中英

使用列名和 ggplot2 创建函数

[英]Creating a function with column names and ggplot2

我想在使用 ggplot 的自定义函数中传递列名,以便我可以重新创建图形。

错误指出:

Error: All columns in a tibble must be 1d or 2d objects: * Column `x` 

如何更新我的函数以便定义我想要的列?

谢谢。

#DATA AND GRAPH
data("USArrests")
USArrests$IsHigh <- ifelse(USArrests[1] >= 13, 1 ,0)
ggplot(USArrests, aes(x=Assault, fill=factor(IsHigh)))+geom_density(alpha=0.25)+
geom_vline(aes(xintercept=mean(Assault[IsHigh==0],na.rm=T)),color="red",linetype="dashed",lwd=1)+
geom_vline(aes(xintercept=mean(Assault[IsHigh==1],na.rm=T)),color="blue",linetype="dashed",lwd=1)+
scale_x_continuous()+
  theme_classic()


##ATTEMPT AT FUNCITON
Test <- function(DATA, col1, col2){

ggplot(DATA, aes(x=col1, fill=factor(col2)))+
geom_density(alpha=0.25)+
geom_vline(aes(xintercept=mean(col1[col2==0],na.rm=T)),color="red",linetype="dashed",lwd=1)+
geom_vline(aes(xintercept=mean(col1[col2==1],na.rm=T)),color="blue",linetype="dashed",lwd=1)+
scale_x_continuous()+
  theme_classic()
}

#ERROR
Test(USArrests, "Assault", "IsHigh")

首先,在你的参数中有col1并且在函数体中你调用col而不是col1 ,其次你需要使用get()来返回命名对象( col1col2 )的值。 尝试这个...

Test <- function(DATA, col1, col2){
        ggplot(DATA, aes(x=get(col1), fill=factor(get(col2))))+
        geom_density(alpha=0.25)+
        geom_vline(aes(xintercept=mean(get(col1)[get(col2)==0],na.rm=T)),color="red",linetype="dashed",lwd=1)+
        geom_vline(aes(xintercept=mean(get(col1)[get(col2)==1],na.rm=T)),color="blue",linetype="dashed",lwd=1)+
        scale_x_continuous()+
        xlab(label = "Fixed Acidity Level")+
        ggtitle("Distribution of Fixed Acidity Levels")+
        theme_classic()
    }

Test(USArrests, "Assault", "IsHigh")

如果你不想使用get那么...

Test <- function(DATA, col1, col2){

  col1 <- DATA[,col1] 
  col2 <- DATA[,col2]

  ggplot(DATA, aes(x=col1, fill=factor(col2)))+
    geom_density(alpha=0.25)+
    geom_vline(aes(xintercept=mean(col1[col2==0],na.rm=T)),color="red",linetype="dashed",lwd=1)+
    geom_vline(aes(xintercept=mean(col1[col2==1],na.rm=T)),color="blue",linetype="dashed",lwd=1)+
    scale_x_continuous()+
    xlab(label = "Fixed Acidity Level")+
    ggtitle("Distribution of Fixed Acidity Levels")+
    theme_classic()
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM