I am trying to put write a function to generate ggplot plots. Heroka helped me out with getting my function to work. But now I have a question on how I can build an auto label wrapper inside this function. I saw a similar and very useful question on this, but the same code doesn't work inside a function.
I'm reproducing my current function for generating ggplot below:
myfunction = function (data, Variable1) {
ggplot(data=data, aes_string(sprintf("factor(%s)",Variable1), "Variable2"))+
geom_boxplot(fill="grey", colour="black")+
labs(title = sprintf("%s and Variable2", Variable1)) +
labs (x = Variable1, y = "Variable2")
}
When I try to do the below (note that I'm trying to wrap the labels within the call of the ggplot:
myfunction = function (data, Variable1) {
ggplot(data=data, aes_string(sprintf("factor(%s)",Variable1), "Variable2"))+
geom_boxplot(fill="grey", colour="black")+
labs(title = sprintf("%s and Variable2", Variable1)) +
labs (x = Variable1, y = "Variable2")+
# adding the line to wrap the labels
scale_x_discrete(labels = function(x) str_wrap(x, width = 10))
}
It doesn't work (plot still generated, but as if I didn't insert that line) I'm confused as to:
I think I need to change the x in that additional line to my actual variable? in this case that would be
Variable1
, but when I did that it still didn't workSince we are still within the ggplot call, is this an environment issue again? (such as we need to use
aes_string
instead of aes when within a function since we are in a local environment). However, with the additional of an extra function within this function, I'm not sure which environment we are in and how to implement the label wrapping line.