Multiple Lines for Text per Legend Label in ggplot2

前端 未结 1 1108
感情败类
感情败类 2020-12-08 08:20

I\'m trying to deal with very long labels for a legend in a bar plot (see picture included and the code i used to produce it. I need to break them down in multiple (rows of)

相关标签:
1条回答
  • 2020-12-08 08:22

    You can use str_wrap for automated wrapping of long strings or you can hard code breaks by adding \n (the line break character) to a string. To add space between the legend keys, you can use the legend.key.height theme element. Here's an example with the built-in iris data frame:

    library(stringr)
    library(tidyverse)
    
    # Create long labels to be wrapped
    iris$Species = paste(iris$Species, 
                         "random text to make the labels much much longer than the original labels")
    
    ggplot(iris, aes(Sepal.Length, Sepal.Width, colour=str_wrap(Species,20))) +
      geom_point() +
      labs(colour="Long title shortened\nwith wrapping") +
      theme(legend.key.height=unit(2, "cm"))
    

    0 讨论(0)
提交回复
热议问题