r - Refering to a variable of the data frame passed in the 'data' parameter of ggplot function -
i use variable of dataframe passed data
parameter of function ggplot
in ggplot2
function in same call.
for instance, in following example want refer variable x
in dataframe passed data
parameter in ggplot
in function scale_x_continuous
such 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 error :
error in seq(min(x)) : object 'x' not found
which understand. of course can avoid problem 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 don't want forced define object df
outside call ggplot. want able directly refer variables in dataframe passed in data
.
thanks lot
you write helper function initilialize plot
helper <- function(df, col) { ggplot(data = df, mapping = aes_string(x = col)) + scale_x_continuous(breaks = seq(min(df[[col]]), max(df[[col]]))) }
and call
helper(data.frame(x = samp), "x") + geom_bar()
Comments
Post a Comment