2

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

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Exactly, thanks @Chase. Following code work perfectly: ggplot(diamonds,aes(x=price)) + geom_histogram(aes_string(y = y.scale),binwidth=1000) + facet_wrap(~color)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.