Home > Net >  ggplot: Insert linebreak when label is too long
ggplot: Insert linebreak when label is too long

Time:08-26

I have to produce a scatter plot with many points. I am already using the package "ggrepel" in order to avoid overlapping, but it sometimes still doesnt work. Is there a possibility to insert a linebreak into the labels (e.g. after a certain length)?

Thanks for help!



items <- c("A long description of the item",
           "Another very long text descrbing the item",
           "And finally another one ",
           "This text exceeds the available space by far",
           "Incredibly long text",
           "Here we go with another one",
           "A linebreak would help here",
           "This has at least 20 characters")

items <- rep(items, 4)

df <- data.frame(
                  descs = items,
                  x = rnorm(n = length(items), mean = 2, sd = 2),
                  y = rnorm(n = length(items), mean = 2, sd = 2),
                  cat = as.factor(runif(length(items), min = 1, max = 6))
                 )


library(ggplot2)
library(tidyverse)
library(ggrepel)

df %>% ggplot(aes(x = x, y = y, color = cat))   geom_point()  
  #geom_text(aes(label = descs))  
  geom_text_repel(aes(label = descs))  
  theme_light()  
  theme(legend.position="none")

rm(items)
rm(df)


CodePudding user response:

You could use stringr::str_wrap to achieve line breaks at an appropriate point. For example, to limit lines to 20 characters, you can do:

df %>% 
  ggplot(aes(x = x, y = y, color = cat))   geom_point()  
  geom_text_repel(aes(label = stringr::str_wrap(descs, 20)))  
  theme_light()  
  theme(legend.position = "none")

enter image description here

  • Related