1

I have my data:

new_df <-  structure(list(Group = c("k__Bacteria;p__Proteobacteria;c__Alphaproteobacteria;o__Rhodospirillales;f__Rhodospirillaceae;g__Skermanella", 
"k__Bacteria;p__Proteobacteria;c__Alphaproteobacteria;o__Rhodospirillales;f__Rhodospirillaceae;g__Skermanella", 
"k__Bacteria;p__Proteobacteria;c__Alphaproteobacteria;o__Rhodospirillales;f__Rhodospirillaceae;g__Skermanella", 
"k__Bacteria;p__Proteobacteria;c__Alphaproteobacteria;o__Rhodospirillales;f__Rhodospirillaceae;g__Skermanella"
), Percentile_0 = c(1, 1, 1, 22), Percentile_25 = c(1, 17.5, 
16.75, 37), Percentile_50 = c(1, 23, 29, 39), Percentile_75 = c(9, 
31.75, 33, 41.75), Percentile_100 = c(35, 47, 93, 50), Type = c("CC", 
"CCS", "CS", "SCS")), row.names = c(NA, -4L), class = "data.frame")

I have my plot that looks like this

library(stringr) # for strwrap
bp <- ggplot(data = new_df, aes(x = Group, group = Type, fill = Type)) +
  geom_boxplot(
    stat = "identity",
    aes(
      ymin = Percentile_0,
      lower = Percentile_25,
      middle = Percentile_50,
      upper = Percentile_75,
      ymax = Percentile_100
    )
  ) +
  theme_classic() +
  theme(axis.text.x=element_text(size=rel(0.45), angle=90))+
  labs(x="Taxa", y="Sequence abundance") 

enter image description here

I wanted to wrap the x-axis text. I tried + scale_x_discrete(labels = function(x) str_wrap(x, width = 10)) based on this thread here which doesn't work for me. How do I wrap the axis text by the delimiter semicolon ;?

MAPK
  • 5,635
  • 4
  • 37
  • 88

1 Answers1

3

I think str_wrap needs a space to trigger a new line. Here I add one to each semicolon:

new_df$Group = stringr::str_replace_all(new_df$Group, ";", "; ")

ggplot(data = new_df, 
       aes(x = stringr::str_wrap(Group, 20), 
       group = Type, fill = Type)) +
....
# clearer formatting for posting purposes
theme(axis.text.x=element_text(size=rel(1), angle=0))+
....

enter image description here

Jon Spring
  • 55,165
  • 4
  • 35
  • 53