Can expressions be used inside 'paste0' for ggtitle?

Works:

ggplot(mtcars, aes(x=wt, y=mpg))+
  geom_point() +
  ggtitle(expression(r^2))

Doesn't work inside of paste0:

ggplot(mtcars, aes(x=wt, y=mpg))+
  geom_point() +
  ggtitle(paste0(expression(r^2)))

use the tilde as a separator to combine text with mathematical expression

library(tidyverse)

ggplot(mtcars, aes(x=wt, y=mpg))+
  geom_point() +
  ggtitle(str2expression(paste("r^2"," pasted", sep = "~" )))

This doesn't work inside a paste / paste0 .

ggplot(mtcars, aes(x=wt, y=mpg))+
  geom_point() +
  ggtitle(paste("blah_blah",
                str2expression(paste("r^2"," pasted", sep = "~" ))))




I wonder if there's any work around?

One option is to use html/markdown in conjunction with the {ggtext} package

library(ggplot2)
library(ggtext)

myvar = "bananas"

ggplot(mtcars, aes(x=wt, y=mpg))+
  geom_point() +
  ggtitle(paste0("This is ",myvar," and this is my r<sup>2</sup> model"))+
  theme(
    plot.title = element_markdown()
  )

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

1 Like
ggplot(mtcars, aes(x=wt, y=mpg))+
  geom_point() +
  ggtitle(
                str2expression(paste("blah_blah","r^2"," pasted", sep = "~" )))

image

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.