I would like to use a variable of the dataframe passed to the data
parameter of function the ggplot
in another ggplot2
function in the same call.
For instance, in the following example I want to refer to the variable x
in the dataframe passed to the data
parameter in ggplot
in another function scale_x_continuous
such as in:
library(ggplot2)
set.seed(2017)
samp <- sample(x = 20, size= 1000, replace = T)
ggplot(data = data.frame(x = samp), mapping = aes(x = x)) + geom_bar() +
scale_x_continuous(breaks = seq(min(x), max(x)))
And I get the error :
Error in seq(min(x)) : object 'x' not found
which I understand. Of course I can avoid the problem by doing :
df <- data.frame(x = samp)
ggplot(data = df, mapping = aes(x = x)) + geom_bar() +
scale_x_continuous(breaks = seq(min(df$x), max(df$x)))
but I don't want to be forced to define the object df
outside the call to ggplot. I want to be able to directly refer to the variables in the dataframe I passed in data
.
Thanks a lot