Question

I want to do this eventually:

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)

but I want to use variable names for "..count.." or "..density..". I tried couple things but failed:

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)

Any ideas how to pass variable names into aes()?

Was it helpful?

Solution

I think you're after aes_string() instead of aes(): http://docs.ggplot2.org/current/aes_string.html

i.e.

foo <- "..density.."

ggplot(diamonds, aes(price)) +
  geom_histogram(aes_string(y = foo),binwidth=1000)  + 
  facet_wrap(~color)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top