r - 在ggplot中循环时获取X轴的变量名称?
问题描述
我想知道是否有任何方法可以在每个图形的 x 轴上插入实际对应的变量。在我的实际数据集中,我有 15 个预测变量。因为它不是,对于每个图表,在轴上,我只是犯罪犯罪[,i]。
谢谢!
这是一个最小的可重现示例:
y<- c(1,5,6,2,5,10) # response
x1<- c(2,12,8,1,16,17) # predictor
x2<- c(2,14,5,1,17,17)
crime <- data.frame(x1,x2,y)
for (i in 1:ncol(crime)){
print(ggplot(crime, aes(x = crime[, i], y = y))+
geom_point())
Sys.sleep(2)
}
解决方案
一种选择是names
根据索引获取 ,然后转换为sym
bol 并评估 ( !!
)
for (i in 1:2){ # the first two columns are the 'x' columns
print(ggplot(crime, aes(x = !! rlang::sym(names(crime)[i]), y = y))+
geom_point())
Sys.sleep(2)
}
或者另一种选择是在添加层的同时保留 OP 的代码xlab
for (i in 1:2){ # the first two columns are the 'x' columns
print(ggplot(crime, aes(x = crime[,i], y = y))+
geom_point() +
xlab(names(crime)[i]))
Sys.sleep(2)
}
推荐阅读
- r - 如何在R中的变量的每个级别内找到归一化值
- angular - 单元测试 Angular Material 对话框 - 如何包含 MAT_DIALOG_DATA
- excel-formula - 通过读取多个列返回多个值并根据列选择进行更改
- typescript - Loopback 4:@repository 依赖注入失败(TypeError:无法读取未定义的属性“findOne”)
- c - osmocom asn1c 为 GSM_MAP/TCAP 协议生成的 C 代码中的文件名冲突
- php - Laravel 缓存不存储数据库结果数组
- node.js - 如何在节点中使用带有 typescript 泛型的 IOC 容器?
- automated-tests - option.timeout 忽略等待 Selector.withAttribute
- sql-server - SQL Server - 根据运行总计为字段分配值
- java - java - 如何仅在不使用JDBC,sql的Java中从csv文件中检索数据