debruinf debruinf - 2 months ago 31
R Question

Add line break to axis labels and ticks in ggplot

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 and readable.

As an example:

df <- data.frame(a=LETTERS[1:20], b=rnorm(20), c=rnorm(20), d=rnorm(20))
df_M <- melt(df, id="a")
plot <- ggplot(data=df_M, aes(x=variable, y=a, fill=value) + geom_tile() + scale_fill_gradient(low="green", high="red")
plot


here the x axis is just letters, but if I want to use the full name, the names use a disproportionate amount of space:

plot + theme(axis.text.x=element_text(angle=90))+ scale_x_discrete(breaks=unique(df_M$variable), labels=c("Ambystoma mexicanum", "Daubentonia madagascariensis", "Psychrolutes marcidus"))


So I would like to put a line break in the labels. Preferably in ggplot2 but other solutions are welcome of course.

Thanks!

Answer

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")))

enter image description here