r - 使用列名和 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()
用于返回命名对象(col1
和col2
)的值。尝试这个...
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()
}
推荐阅读
- python - 如何避免 KeyError 丢失字典键?
- c - 提高 Vivado HLS 部门的性能
- java - 在 LinearLayout 中设置重力 - android
- perl - PERL:我从 locatime 中获取 mday 值,如下所示。如何从本地时间获取的 mday 中减去 1
- reactjs - 使用 React UI 和 Spring Boot 服务器实现用户搜索的建议
- html - 更改 DataTables 搜索栏的颜色
- python - Docker 不会安装 Python
- node.js - Nodejs在CSV中编辑单行
- flutter - 在颤动中对齐行内的项目
- javascript - 蒙版更改后光标在错误的位置