A geom_boxplot that has x-axis labels with linebreaks ("\n") works great.
library(ggplot2)
library(latex2exp)
theme_set(theme_grey())
set.seed(10)
df <- data.frame(y=rnorm(120),
x=rep(c("bar",
"long\ncategory\nname",
"longspacesuperscript\n(mm$^{2}$)"
),
each=40)
)
#Normal boxplot labels with line breaks
p1 <- ggplot(data = df, aes(x, y)) +
geom_boxplot() +
scale_x_discrete() +
ggtitle("No latex2exp (TeX command) used line breaks in x axis labels work, alignment ok")
print(p1)
#Boxplot labels using TeX
p2 <- ggplot(data = df, aes(x, y)) +
geom_boxplot() +
scale_x_discrete(labels = latex2exp::TeX) +
ggtitle("Latex2exp (TeX command) affect label alignment??")
print(p2)
# We can change the position of the labels in the plot,
# but not within the textbox that the label seems to be nested in?
p3 <- p2 + theme_set(theme(axis.text.x=element_text(vjust=-1))) +
ggtitle("Latex2exp (TeX command) label position adjusted")
print(p3)
Latex alignment commands in TeX() didnt work \centre \raggedleft etc.
Question(s): How can you change the alignment within the latex2exp::TeX() environment? Does that work in ggplot labels ? (without manually adding the label text, i.e. using default label names based on data (factor) naming, as I sort of did in the example)?
Or maybe a complete work around to have expected behavior and still used LaTeX within ggplot?
Based on comment of shafee I added this expected plot with center alignment and no overriding of the bottom x (similar as first plot but with correct LaTeX interpretation)