invictus invictus - 1 year ago 170
R Question

Asterisk in ggplot's annotate()

Text can be added to a

ggplot
object using
annotate()
. However, I can't figure out how to print an asterisk, since, so far as I understand, the asterisk is used in parsing.

Here is an example. Suppose I ran a nonparametric test, and I want to print the test statistic with its significance level measured in stars. Unfortunately, this does not work:

library(ggplot2)
ggplot(iris, aes(Sepal.Length, Sepal.Width, color=Species)) +
geom_point() +
annotate('text', x = 7, y = 4, label="chi^2 == 2.50***", parse=TRUE)

Error in parse(text = as.character(lab)) : <text>:1:16: unexpected '*'
1: chi^2 == 2.50***


Defining the label outside the plot object - e.g.
lab <- paste0("chi^2 == 2.5","***", sep="")
, then calling
annotate('text', x = 7, y = 4, label=lab, parse=TRUE)
- does not work either.

Is it possible to use the asterisk with
annotate()
?

Edit Sorry, I neglected to mention that I want the Greek letter to be compiled. Ideally the text would appear as $$chi^2 = 2.50***$$

Answer Source

Using a combination of double and single quotes does the trick:

library(ggplot2)
ggplot(iris, aes(Sepal.Length, Sepal.Width, color=Species)) + 
  geom_point() + 
  annotate('text', x = 7, y = 4, label='chi^2 == "2.50***"', parse=TRUE)

You can use single quotes for label =, and double quotes for strings you don't want annotate to parse. Anything outside the double quotes but inside the single quotes will be parsed.

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download