In trying to tweak the output of geom_bar()
, I come across some solutions that include function(x)
as here where the x-axis labels get wrapped by use of stringr:
scale_x_discrete(labels = function(x) str_wrap(x, width = 10))
What exactly is function(x)
doing? It is simply saying that it's followed by a function to apply to x? But then what's x exactly, since it's the data defined in the original ggplot aes call, while here it's the label text?
Just when I think I understand something in R...
TIA.
CodePudding user response:
The entire expression goes together
function(x) str_wrap(x, width = 10)
is an anonymous function in R (a function with no name). The labels=
parameter of scale_x_discrete
can take a vector of characters, or a function. If a function, ggplot will pass in the default breaks as input It doesn't have to be named "x", you can call it whatever you want. So this would work as well
scale_x_discrete(labels = function(default_breaks) str_wrap(default_breaks, width = 10))
This is documented on the ?ggplot2::scale_x_discrete
help page.