'r add math symbol to x axis text

I am trying to add a math symbol (sum) to some texts in x-axis.

For example, if this is my plot.

data(iris)
p1 <- ggplot(iris, aes(x=Species, y=Sepal.Length)) + 
  geom_boxplot()
p1

What I am trying to accomplish is this. Not sure how to do this, any suggestions appreciated. Thanks in advance.

enter image description here



Solution 1:[1]

This is almost certainly a duplicate, but I couldn't find the answer when I searched, so here is a potential solution:

library(tidyverse)

iris_correctly_labelled <- iris %>%
  mutate(Species = case_when(Species == "setosa" ~ paste0("\u2211", "setosa"),
                             Species == "versicolor" ~ "versicolor",
                             Species == "virginica" ~ paste0("\u2211", "virginica")))

p1 <- ggplot(iris_correctly_labelled,
             aes(x=fct_reorder(Species, Sepal.Length), y=Sepal.Length)) + 
  geom_boxplot() +
  theme(axis.title.x = element_blank(),
        text = element_text(size = 16))
p1

Created on 2022-05-13 by the reprex package (v2.0.1)

Does that solve your problem?

Solution 2:[2]

You could also consider using the latex2exp package's TeX function which allows you to add more complicated symbols and formulae using LaTeX's syntax to plot texts and titles:

data(iris)
library(ggplot2)
library(latex2exp)

x_labs <- c(TeX(r'($\Sigma$ setosa)'), "versicolor", TeX(r'($\Sigma$ virginica)'))

p1 <- ggplot(iris, aes(x=Species, y=Sepal.Length)) + 
  geom_boxplot() + 
  scale_x_discrete(labels = x_labs) + 
  theme() # adjust text size to suit

p1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Stuart Demmer