Search code examples
rggplot2ggpubr

ggpubr's stat_cor() - avoid space before comma when using a manual label


I am trying to create some rather hacky plots with custom labels using stat_cor() in my ggplot from the package ggpubr. Unfortunately, pasting together ..rr.label.. and ..p.label.., separated with a comma, results in a space after and before the comma, which is a bit ugly. "Conveniently", the issue is (accidentally?) illustrated in the examples provided at ?stat_cor:

library(ggpubr)

# Load data
data("mtcars")
df <- mtcars
df$cyl <- as.factor(df$cyl)

ggscatter(df, x = "wt", y = "mpg", add = "reg.line") +
 stat_cor(
   aes(label = paste(..rr.label.., ..p.label.., sep = "~`,`~")),
  label.x = 3
)

Getting rid of the first ~ in sep will result in an error, because the comma is unexpected in italic(R)^2~`=`~0.75`,`. I also tried using paste0() instead of paste(), but that of course does not work (unexpected symbol in italic(R)^2~`=`~0.75italic).

Is there a way to get rid of the space before the comma?

Thanks in advance!


Solution

  • Simply use a * aka "times" instead of a ~ before the comma to create a proper plotmath expression without adding a space:

    library(ggpubr)
    
    # Load data
    data("mtcars")
    df <- mtcars
    df$cyl <- as.factor(df$cyl)
    
    ggscatter(df, x = "wt", y = "mpg", add = "reg.line") +
      stat_cor(
        aes(label = paste(..rr.label.., ..p.label.., sep = "*`,`~")),
        label.x = 3
      )
    

    enter image description here