Home > Net >  ggplot x axis label too long and need line break
ggplot x axis label too long and need line break

Time:05-03

I'trying to shorten my x axis label.

I want to change the x label with two line, with same text length

How can I shorten my text and show in two lines?

enter image description here

CodePudding user response:

You could use word to take the first few words and str_wrap to control the number of characters per line like this:

library(tidyverse)

tribble(
  ~label, ~value,
  "my_very_long_label", 10,
  "even_longer_label_with more_words", 10,
  "really_quite_verbose_label", 10
) |> 
  mutate(label = str_replace_all(label, "_", " "),
         label = word(label, 1, 3),  # Use only the first 3 words
         label = str_wrap(label, 15) # Only 15 characters per line
         ) |>  
  ggplot(aes(label, value))  
  geom_col()

Created on 2022-04-28 by the reprex package (v2.0.1)

  • Related