cardboard12
cardboard12

Reputation: 47

How to make an expression go onto multiple lines for axis labels in ggplot?

For the following piece of code, I want to be able to make it so group_name goes onto multiple lines in the axis label. Similar to how str_wrap works in R.

I've struggled to make it work in the make_labels2 function and also outside of it. Not sure if there's a best approach to take?

Any help is much appreciated.

group_name = sprintf("A[%i*x This is a long string and I would like it to look nicely wrapped on the x axis label]", rep(1:4,each=2)) #added long string from code solution
group_name3 = sprintf("A[%i*y]", rep(1:4,each=2))

make_labels2 <- function(value) {
  x <- as.character(value)
  #do.call(expression, lapply(x, function(y) bquote(atop(bold(.(y)), "this"~italic("degree")~x)) ))
  do.call(expression, lapply(x, function(y) bquote(atop(bold(.(strsplit(y,split="_")[[1]][[1]]))~"_"~italic(.(strsplit(y,split="_")[[1]][[2]])), "this"~italic("degree")~x)) ))
}

mydata2 <- data.frame(mygroup = group_name, 
                      mygroup3 = group_name3,
                      mysubgroup = factor(c("Yes", "No"), 
                                          levels = c("Yes", "No")), 
                      value = c(60,40,90,10,55,45,88,12))
mydata2$mygrp2 <- paste0(mydata2$mygroup,"_",mydata2$mygroup3)

ggplot(mydata2, aes(mygrp2, value, fill = mysubgroup)) + 
  geom_bar(position = "dodge", width = 0.5, stat = "identity")+ 
  coord_flip() + 
  scale_x_discrete(labels = make_labels2)

Upvotes: 1

Views: 801

Answers (1)

Sinh Nguyen
Sinh Nguyen

Reputation: 4487

To make a label into a new line use "\r\n" would create that. This is an example

library(ggplot2)

group_name = sprintf("A[%i*x This is a long string and I would like it to look nicely wrapped on the x axis label]", rep(1:4,each=2)) #added long string from code solution
group_name3 = sprintf("A[%i*y]", rep(1:4,each=2))

make_labels2 <- function(value) {
  x <- as.character(value)
  #do.call(expression, lapply(x, function(y) bquote(atop(bold(.(y)), "this"~italic("degree")~x)) ))
  x <- lapply(x, function(x) { paste(strwrap(x, width = 10), collapse = "\r\n") })
  x <- do.call(expression, lapply(x, function(y) bquote(atop(bold(.(strsplit(y,split="_")[[1]][[1]]))~"_"~italic(.(strsplit(y,split="_")[[1]][[2]])), "this"~italic("degree")~x)) ))
  x
}

mydata2 <- data.frame(mygroup = group_name, 
  mygroup3 = group_name3,
  mysubgroup = factor(c("Yes", "No"), 
    levels = c("Yes", "No")), 
  value = c(60,40,90,10,55,45,88,12))
mydata2$mygrp2 <- paste0(mydata2$mygroup,"_",mydata2$mygroup3)

ggplot(mydata2, aes(mygrp2, value, fill = mysubgroup)) + 
  geom_bar(position = "dodge", width = 0.5, stat = "identity")+ 
  coord_flip() + 
  scale_x_discrete(labels = make_labels2)

Output graph

enter image description here

Upvotes: 1

Related Questions