我想最终这样做:
library(ggplot2)
density=TRUE
if (density) {ggplot(diamonds,aes(x=price)) + geom_histogram(aes(y=..density..),binwidth=1000) + facet_wrap(~color)
} else ggplot(diamonds,aes(x=price)) + geom_histogram(aes(y=..count..),binwidth=1000) + facet_wrap(~color)
但我想为“..count ..”或“..density ..”使用变量名。我尝试了几件事但失败了:
if (density) {y.scale ="..density.."} else y.scale ="..count.."
ggplot(diamonds,aes(x=price)) + geom_histogram(aes(y=get(y.scale)),binwidth=1000) + facet_wrap(~color)
ggplot(diamonds,aes(x=price)) + geom_histogram(aes(as.formula(paste("y=",y.scale))),binwidth=1000) + facet_wrap(~color)
如何将变量名称传递给aes()?
答案 0 :(得分:2)
我认为你是aes_string()
而不是aes()
:http://docs.ggplot2.org/current/aes_string.html
即。
foo <- "..density.."
ggplot(diamonds, aes(price)) +
geom_histogram(aes_string(y = foo),binwidth=1000) +
facet_wrap(~color)