cardboard12
cardboard12

Reputation: 47

Is there a way in ggplot to have 2 different variables in same x axis labels with different font type?

I'm trying to get different fonts in the x axis labeling of ggplot. I can see from the following link: X-axis tick labels different font size and font face ggplot that it's likely bquote and atop. However, I'm not entirely sure how to go about this.

The following is some code also from stack overflow here: ggplot displaying expression in x axis

group_name = sprintf("A[%i*x]", rep(1:4,each=2))
group_name3 = sprintf("A[%j*x]", 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))))
}


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))

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

I want to be able to use group_name3 and just concatenate it onto the group_name. Struggling to find the best way. With group_name3 not being bold.

Any help is greatly appreciated.

Thanks in advance.

Upvotes: 0

Views: 146

Answers (1)

YBS
YBS

Reputation: 21349

Perhaps you are looking for this

group_name = sprintf("A[%i*x]", rep(1:4,each=2))
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)

output

Upvotes: 1

Related Questions