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!
The “\n” symbol can be inserted into the position within each component, to insert a line break. The mappings in the ggplot method can be assigned to the labels of the data frame in order to assign the corresponding text at the respective coordinates of the data frame.
To alter the labels on the axis, add the code +labs(y= "y axis name", x = "x axis name") to your line of basic ggplot code. Note: You can also use +labs(title = "Title") which is equivalent to ggtitle .
Plot the rectangular data as a color-encoded matrix. Use tick_params() for changing the appearance of ticks and tick labels. Use left=false and bottom=false to remove the tick marks.
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")))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With