I was wondering how to put a subscript in my x-axis tick labels. Not in the axis label, as in most other posts, hence from the values already in the data frame.
Here is a reproducible code example, I would like the letters in brackets to be subscripts.
p_t<- c(rep("FW - P[H]",3),rep("FW - P[L]",3),rep("FW - F",3),rep("FW - SSWB",3),rep("C - F",3),rep("C - P[L]",3),rep("C - P[H]",3))
s_t<-rep(c("A","B","C"),7)
c_t <-c(0,1,2,+
0,3,2,+
0,4,3,+
0,3,4,+
0,6,5,+
0,2,4,+
0,7,2)
df_t1<-data.frame(p_t,s_t,c_t)
ggplot(data=df_t1,aes(y=c_t, x=p_t,fill = s_t))+
geom_bar(stat="identity",
color="black")
A possible approach is to use the recently released package 'ggtext', but its use requires a change to the coding of the subscripts in the example data as 'ggtetxt' implements support for Markdown and HTML markup. In this first code chunk I changed the example data, but if the data are as in the question, gsub()
can be used, as shown in the second code chunk, to replace the square brackets by the HTML coding for subscripts on-the-fly.
library(ggplot2)
library(ggtext)
p_t <- c(rep("FW-P<sub>H</sub>", 3), rep("FW-P<sub>L</sub>", 3), rep("FW-F", 3),
rep("FW-SSWB", 3), rep("C-F", 3), rep("C-P<sub>L</sub>", 3),
rep("C-P<sub>H</sub>", 3))
s_t <- rep(c("A", "B", "C"), 7)
c_t <- c(0, 1, 2, +0, 3, 2, +0, 4, 3, +0, 3, 4, +0, 6, 5, +0, 2, 4, +0, 7, 2)
df_t1 <- data.frame(p_t, s_t, c_t)
ggplot(data = df_t1, aes(y = c_t, x = p_t, fill = s_t)) +
geom_bar(stat = "identity",
color = "black") +
theme(axis.text.x = element_markdown())
String substitution can be done on-the-fly in scale_x_discrete()
so that the conversion to HTML markup can also be automated if desired.
p_t <- c(rep("FW - P[H]", 3), rep("FW - P[L]", 3), rep("FW - F", 3),
rep("FW - SSWB", 3), rep("C - F", 3), rep("C - P[L]", 3),
rep("C - P[H]", 3))
s_t <- rep(c("A", "B", "C"), 7)
c_t <- c(0, 1, 2, +0, 3, 2, +0, 4, 3, +0, 3, 4, +0, 6, 5, +0, 2, 4, +0, 7, 2)
df_t1 <- data.frame(p_t, s_t, c_t)
ggplot(data = df_t1, aes(y = c_t, x = p_t, fill = s_t)) +
geom_bar(stat = "identity",
color = "black") +
scale_x_discrete(labels = function(x) {gsub("\\[", "<sub>", gsub("\\]", "</sub>", x))}) +
theme(axis.text.x = element_markdown())
Note: The tick labels are not exactly the same as when using R expressions as the characters are here retained unchanged and spacing around dashes is neither added nor modified. In this case dashes are visibly shorter.