I\'m looking for a way to use long variable names on the x axis of a plot. Of course I could use a smaller font or rotate them a little but I would like keep them vertical a
In addition to Joe's answer this also works
myplot + scale_x_discrete(labels = c("Ambystoma\nmexicanum")
via str_replace_all()
, replace 'foo_your_symbol_delim'
with a space delim ' '
via str_wrap
from stringr
library, with width prespecified at 40
, split at space delimiter ' '
, wrap the pieces, and paste
library(stringr)
...
+ scale_x_discrete(labels = function(x) str_wrap(str_replace_all(x, "foo" , " "),
width = 40))
If you don't want a break at each space, you could alternatively use the \n
(new line) within the call to scale_x_continuous:
my.labels <- c("Ambystoma\nmexicanum",
"Daubentonia madagascariensis",
"Psychrolutes marcidus") # first create labels, add \n where appropriate.
myplot +
scale_x_discrete(labels= my.labels)
Note that only the first name (Ambystoma mexicanum) will break using the new line command (\n
).
You can add your own formatter ( see scales
package for more examples). Here I replace any space in your x labels by a new line.
addline_format <- function(x,...){
gsub('\\s','\n',x)
}
myplot +
scale_x_discrete(breaks=unique(df_M$variable),
labels=addline_format(c("Ambystoma mexicanum",
"Daubentonia madagascariensis", "Psychrolutes marcidus")))
I'd also add to @SoilSciGuy's answer that if you only want to modify one label, you can do it inside scale_x_discrete()
.
myplot + scale_x_discrete(labels = c("Ambystoma mexicanum" = "Ambystoma\nmexicanum")