Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
767 views
in Technique[技术] by (71.8m points)

r - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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','
',x)
}

myplot + 
    scale_x_discrete(breaks=unique(df_M$variable), 
    labels=addline_format(c("Ambystoma mexicanum", 
                        "Daubentonia madagascariensis", "Psychrolutes marcidus")))

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...