Home > Back-end >  Latex2exp (TeX command) affects label alignment in ggplot?
Latex2exp (TeX command) affects label alignment in ggplot?

Time:07-12

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)

p1 correct alignment and line breaks

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

p2 labels are left aligned and superscript is filled out?

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

Latex2exp (TeX command) label position adjustnment (vjust=-1, hjust = 0.5) works but not within the TeXbox??

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?

enter image description here 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)

CodePudding user response:

You can obtain that plot using html or markdown math expression along with functions from ggtext package.

library(ggplot2)
library(ggtext)

set.seed(10)
df <- data.frame(
    y = rnorm(120),
    x = rep(
        c(
            "bar",
            "long<br>category<br>name",
            "longspacesuperscript<br>(mm<sup>2</sup>)"
        ),
        each = 40
    )
)

ggplot(data = df, aes(x, y))  
    geom_boxplot()  
    ggtitle("This works using html expression with ggtext package")  
    theme(
        axis.text.x = ggtext::element_markdown()
    )

a plot with latexlike expression in axis label

  • Related