Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add line break to axis labels and ticks in ggplot

Tags:

r

ggplot2

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!

like image 366
debruinf Avatar asked Nov 21 '13 14:11

debruinf


People also ask

How do I insert a line break in ggplot2?

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.

Which arguments can be used to add labels in Ggplot?

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 .

How do I get rid of Xticks in Seaborn?

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.


1 Answers

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

like image 151
agstudy Avatar answered Sep 21 '22 11:09

agstudy