Refering to a variable of the data frame passed in the 'data' parameter of ggplot function

萝らか妹 提交于 2019-12-11 05:14:18

问题


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


回答1:


You could write a helper function to initilialize the 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 then call

helper(data.frame(x = samp), "x") + geom_bar()


来源:https://stackoverflow.com/questions/43280809/refering-to-a-variable-of-the-data-frame-passed-in-the-data-parameter-of-ggplo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!