Home > Software engineering >  R add new line to expression vector
R add new line to expression vector

Time:11-25

I have a boxplot with four groups and I want to add a name to each group that consists of two lines and includes subscripts. Therefore I tried using bquote():

#sample data
groups = matrix(1:40,ncol=4)

#create group names
names = as.expression(sapply(1:4, function(x){
  letter = LETTERS[x]
  name = bquote(atop(.(letter),num[.(x)] == .(x)))
  return(name)
}))

boxplot(groups, names = names)

Which gives me the following result: enter image description here

I'm almost pleased with the result. However, atop() has some weird spacing so that the top line (with letters A-D) lies on top of the outer boundary. I couldn't find any solution working for me to solve this problem.

I also tried the following:

#Alternative Approach (not working)
names = parse(text=paste(LETTERS[1:4],"\n","num[", 1:4, "]", sep=""))

In this case, the addition of "\n" (new line) simply breaks the names variable from length 4 into length 8.

I have absolutely no idea how to solve this seemingly simple problem. Help is much appreciated!

CodePudding user response:

How about this:

#sample data
groups = matrix(1:40,ncol=4)

#create group names
names = as.expression(sapply(1:4, function(x){
  letter = LETTERS[x]
  name = bquote(atop(.(letter),num[.(x)] == .(x)))
  return(name)
}))

boxplot(groups, names = LETTERS[1:4])
mtext(parse(text=paste("num[", 1:4, "]", sep="")), side=1, at=1:4, line=2)

Created on 2022-11-24 by the reprex package (v2.0.1)

CodePudding user response:

Another option is to translate this plot to ggplot2:

library(tidyverse)

groups = matrix(1:40,ncol=4)

#create group names
names = as.expression(sapply(1:4, function(x){
  letter = LETTERS[x]
  name = bquote(atop(.(letter),num[.(x)] == .(x)))
  return(name)
}))


as.data.frame.matrix(groups) |>
  `colnames<-`(LETTERS[1:4]) |>
  pivot_longer(everything()) |>
  ggplot(aes(name, value)) 
  geom_boxplot(fill = "grey") 
  scale_x_discrete(labels = names) 
  labs(x = "", y = "") 
  theme_bw() 
  theme(panel.grid = element_blank())

  •  Tags:  
  • r
  • Related