0

i used iris data for an example

`

    iris %>%    
ggplot(aes(Sepal.Length,
                 fill = Species))+
  geom_density(alpha = .6,
               bw = 0.5)+
  theme_classic()+
  annotate("text", 
           x = 7, 
           y = c(.55, .60),
           size = 4,
           label = c(
             paste0("Mean = ", round(mean(iris$Sepal.Length),4), " cm"),
             paste0("r = ", round(cor(iris$Sepal.Length, iris$Sepal.Width),2), "")))

` plot

I try use force italic using Expression function, but does't work.

1 Answers1

1

Adding parse=TRUE and using ?plotmath notation you could do:

EDIT: Getting a "," as decimal mark is a bit tricky. In the code below I use gsub to replace the "." by "*','*".

library(ggplot2)

mean <- round(mean(iris$Sepal.Length), 4)
mean <- gsub("\\.", "*','*", mean)

cor <- round(cor(iris$Sepal.Length, iris$Sepal.Width), 2)
cor <- gsub("\\.", "*','*", cor)

ggplot(iris, aes(Sepal.Length,
                 fill = Species
)) +
  geom_density(
    alpha = .6,
    bw = 0.5
  ) +
  theme_classic() +
  annotate("text",
           x = 7,
           y = c(.55, .60),
           size = 4,
           label = c(
             paste0("Mean == ", mean, "~cm"),
             paste0("italic(r) == ", cor, "")
           ),
           parse = TRUE
  )

stefan
  • 90,330
  • 6
  • 25
  • 51
  • i try this, but does't work. Console return this message when i put parse = TRUE: Error in parse(text = text[[i]]) : :1:10: ',' inesperado 1: Mean == 5, – Matheus Pacheco Nov 06 '22 at 18:39
  • I try extract value from a data.frame, and put value in an annotation. I selected a line and column inside an a data.frame[1,2] – Matheus Pacheco Nov 06 '22 at 18:42
  • Hi Matheus. The issue is not with `parse=TRUE`. Using `plotmath` could be a bit tricky. From the error message I guess that you want to add a "," as decimal mark. While plotmath works fine with a "." as decimal mark, getting a "," is a bit more tricky, i.e. for a comma you have to do e.g. `"5*','*23"`. See my edit. – stefan Nov 06 '22 at 19:04