Search code examples
rplotlabel

How to add a subscript in R


I am formatting the labeling for some of my graphs in R. This is the code that I use to format my points and labels.

point_4 <- list(scale_shape_manual(
  values = c(18, 15, 18, 17),
  name = "Treatment",
  labels = c("Control", "MET 0-8wks", "MET 0-4wks", "MET 4-8wks")
))

I use this to make "line_graph_4_theme2()" that I apply and it works great:

graph <- ggplot(data=mydata, aes(x=weeks, y=bw, group = rx, color = rx, linetype = rx, shape = rx))+
  stat_summary(fun = "mean", geom = "line", lwd = rel(1))+
  stat_summary(fun = mean,
               geom = "pointrange",
               fun.max = function(x) mean(x) + sd(x) / sqrt(length(x)),
               fun.min = function(x) mean(x) - sd(x) / sqrt(length(x)))+
  stat_summary(fun = "mean", geom = "point", size = rel(2), fill = "white", stroke = rel(1.1))+
  ggtitle("Title")+
  labs(subtitle = " ", x = " Age (Weeks) ", y = "Body Mass (g)", color = "rx") +
  scale_x_discrete(labels = c("5","6", "7", "8", "9","10", "11", "12", "13", "14","15","16","17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27"))+
  line_graph_4_theme2()
graph

This code gives me a graph with the correct labels "Control", "MET 0-8wks", "MET 0-4wks", "MET 4-8wks" for each group.

I want to be able to add a subscript to the label names MET0-8wks etc. for the other groups, is this possible?

I have see examples that use

main=expression('title'[2])

I just do not know how I would add that to my line of : labels = c("Control", "MET 0-8wks", "MET 0-4wks", "MET 4-8wks")


Solution

  • You will need to supply the labels argument a vector of expression objects:

    Here is a reference for how to write these expressions.

    library(ggplot2)
    
    my_label_expressions <- c(
      "Control",
      expression("MET"["0-8wks"]),
      expression("MET"["0-4wks"]),
      expression("MET"["4-8wks"])
    )
    
    data.frame(
      x = rnorm(100),
      y = rnorm(100),
      s = sample(LETTERS[1:4], 100, TRUE)
    ) |>
      ggplot(aes(x, y, shape = s)) + 
      geom_point() + 
      scale_shape_discrete(labels = my_label_expressions)
    

    Created on 2024-04-14 with reprex v2.1.0