Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to wrap an axis title that also has mathematical notation in ggplot2?

The title of my y-axis is long and includes mathematical notation at the end of it. Ideally, the title would occupy 2 rows with the top saying "Long Title Example" and the bottom saying "with Mathematical Operation (% yr-1)". How can I wrap the y-axis title?

I have seen this SO question but I can not seem to get it to work when there is mathematical notation in the title.

Example figure with a long title that includes mathematical notation

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

library(ggplot2)

ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point(shape = 21, size = 4, aes(fill = factor(Species))) +
  stat_smooth(method = 'lm', se = F, color = "red") +
  ylab(expression(Long~Title~Example~with~Mathematical~Operation~("%"~yr^-1))) +
  xlab("Species") +
  labs(fill = "Species") +
  scale_y_continuous(breaks = seq(0,5,1), limits = c(0,5)) +
  scale_x_continuous(breaks = seq(0,8,1), limits = c(0,8)) +
  theme_bw() +
  theme(panel.grid = element_blank(),
        text = element_text(size = 18, color = "black"),
        axis.text.x = element_text(size = 18, color = "black"),
        axis.text.y = element_text(size = 18, color = 'black'),
        legend.title.align = 0.5,
        legend.position = c(0.15,0.2))

>Solution :

Here is a potential solution:

library(ggplot2)

# x axis split over two lines
ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point(shape = 21, size = 4, aes(fill = factor(Species))) +
  stat_smooth(method = 'lm', se = F, color = "red") +
  ylab(expression(atop(Long~Title~Example,
                       with~Mathematical~Operation~("%"~yr^"-1")))) +
  xlab("Species") +
  labs(fill = "Species") +
  scale_y_continuous(breaks = seq(0,5,1), limits = c(0,5)) +
  scale_x_continuous(breaks = seq(0,8,1), limits = c(0,8)) +
  theme_bw() +
  theme(panel.grid = element_blank(),
        text = element_text(size = 18, color = "black"),
        axis.text.x = element_text(size = 18, color = "black"),
        axis.text.y = element_text(size = 18, color = 'black'),
        legend.title.align = 0.5,
        legend.position = c(0.15,0.2))
#> `geom_smooth()` using formula 'y ~ x'

Created on 2022-03-14 by the reprex package (v2.0.1)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading