..count ..或..density ..作为ggplot2中的变量名

时间:2013-06-03 19:51:42

标签: r ggplot2 histogram density-plot

我想最终这样做:

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()?

1 个答案:

答案 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)