Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math symbol error in geom_text

Tags:

math

r

ggplot2

Inserting a math symbol to the text should not be so complicated I supposed!

OTH, even looking similar examples ggplot2 facet_wrap with mathematical expression

still I am not able to insert Ω (Omega) symbol to the geom_text!

Suppose you have basic scatter plot and you want to add mean value with (Omega) math symbol to each facet,

mean.Petal <- aggregate(iris["Petal.Width"], iris["Species"], mean)
    Species     Petal.Width
1     setosa       0.246
2 versicolor       1.326
3  virginica       2.026

ggplot(iris) +
  geom_point(aes(y=Sepal.Length,x=Sepal.Width ,col=factor(Species))) + 
  facet_wrap(~ Species)+
  geom_text(data = mean.Petal, parse = TRUE,
            aes(x = 4.5, y = 7, label=sprintf('mean_Petal=%.2f %s', 
                                               round(Petal.Width,digits=2),'Omega')))

Error in parse(text = as.character(lab)) : :1:17: unexpected symbol 1: mean_Petal=0.25 Omega

Another try

geom_text(data = mean.Petal, parse = TRUE,
          aes(x = 4.5, y = 7, label=paste('mean_Petal=', 
                                  round(Petal.Width,digits=2),expression(Omega),sep=' ')))

Error in parse(text = as.character(lab)) : :1:18: unexpected symbol 1: mean_Petal= 0.25 Omega

like image 470
Alexander Avatar asked Sep 07 '25 00:09

Alexander


1 Answers

When using geom_text with parse = TRUE, you want to put together a string that corresponds to a plotmath expression, so you can do:

ggplot(iris) +
    geom_point(aes(y=Sepal.Length,x=Sepal.Width ,col=factor(Species))) + 
    facet_wrap(~ Species)+
    geom_text(data = mean.Petal, parse = TRUE,
              aes(x = 3, y = 7, 
                  label=paste("'Mean petal' ==", round(Petal.Width, digits=2), "* Omega")))
like image 141
Marius Avatar answered Sep 10 '25 06:09

Marius