HBat
HBat

Reputation: 5682

..count.. or ..density.. as variable name in ggplot2

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

Upvotes: 2

Views: 2416

Answers (1)

Chase
Chase

Reputation: 69151

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)

Upvotes: 3

Related Questions