Add line break to axis labels and ticks in ggplot

后端 未结 5 885
难免孤独
难免孤独 2020-11-29 03:10

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

相关标签:
5条回答
  • 2020-11-29 03:24

    In addition to Joe's answer this also works

    myplot + scale_x_discrete(labels = c("Ambystoma\nmexicanum")
    
    0 讨论(0)
  • 2020-11-29 03:28

    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))
    
    0 讨论(0)
  • 2020-11-29 03:34

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

    0 讨论(0)
  • 2020-11-29 03:38

    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

    0 讨论(0)
  • 2020-11-29 03:50

    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")
    
    0 讨论(0)
提交回复
热议问题