R:使用geom_行访问函数中的列名
我有以下使用R:使用geom_行访问函数中的列名,r,ggplot2,R,Ggplot2,我有以下使用lappy生成的绘图列表。在函数subset和aes\u string中,我似乎没有问题传递对象I(列名): 不幸的是,xintercept在aes中不起作用,因此对象实际上不存在于geom\u vline的环境中 您可以将其用作快速修复: cols <- colnames(mtcars) lapply(cols[2:length(cols)], function(i) { Mean = with(mtcars, mean(get(i), na.rm=T));
lappy
生成的绘图列表。在函数subset
和aes\u string
中,我似乎没有问题传递对象I
(列名):
不幸的是,
xintercept
在aes
中不起作用,因此对象实际上不存在于geom\u vline
的环境中
您可以将其用作快速修复:
cols <- colnames(mtcars)
lapply(cols[2:length(cols)],
function(i) { Mean = with(mtcars, mean(get(i), na.rm=T));
ggplot(subset(mtcars, get(i)>0), aes_string(x=i)) +
geom_histogram() +
geom_vline(xintercept=Mean,
color="red", linetype="dashed", size=1)
}
)
cols 0),aes_字符串(x=i))+
geom_直方图()+
几何线(xintercept=平均值,
color=“red”,linetype=“虚线”,大小=1)
}
)
您可以使用aes\u字符串
,就像您在x
中所做的一样
lapply(cols[2:length(cols)], function(i) {
ggplot(subset(mtcars, get(i)>0), aes_string(x=i)) +
geom_histogram() +
geom_vline(
aes_string(xintercept = paste0("mean(", i, ", na.rm = TRUE)")),
color = "red", linetype="dashed", size = 1)
})
+1是一个很好的解决方案。我只想补充一点,这里的文档中有一些有趣的东西。虽然
xintercept
未被列在geom\u vline
的美学“理解”项下,但如果您将其放入aes
(事实上,example(geom\u vline)
中提供的一个示例使用它),它确实有效。
cols <- colnames(mtcars)
lapply(cols[2:length(cols)],
function(i) { Mean = with(mtcars, mean(get(i), na.rm=T));
ggplot(subset(mtcars, get(i)>0), aes_string(x=i)) +
geom_histogram() +
geom_vline(xintercept=Mean,
color="red", linetype="dashed", size=1)
}
)
lapply(cols[2:length(cols)], function(i) {
ggplot(subset(mtcars, get(i)>0), aes_string(x=i)) +
geom_histogram() +
geom_vline(
aes_string(xintercept = paste0("mean(", i, ", na.rm = TRUE)")),
color = "red", linetype="dashed", size = 1)
})