Paulo E. Cardoso
Paulo E. Cardoso

Reputation: 5856

parsing expression in geom_text: character, number and special characters

My Problem

I'd like to annotate each facet of a ggplot() with a expression that is combinination of values resulting from a statistical test. I'm not being able to get the string parsed within a geom_text().

A similar problem was partially covered here. Unfortunately I'm not being able to apply that specific example.

My Objective

parsing a expression combine numbers, characters and special characters. in this case, lab2 of example below.

Example

p <- ggplot(mtcars, aes(mpg, wt)) + geom_point()

custom_label <- data.frame(cyl = c(4,6,8),
                           wt = c(5,5,5),
                           lab = c('X^2','X^2','X^2'),
                           lab2 = c('X^2: 18.5342, p =3e-04',
                                   'X^2: 4.7512, p =0.1909',
                                   'X^2: 15.3266, p =0.0016'))
p + facet_grid(. ~ cyl) +
  geom_text(data = custom_label, aes(x=30, y=wt, label = lab2), size = 3, parse = T)

This works fine with using custom_label$lab but fails with lab2.

I'd appreciate any help with this. Please let me know if I'm being clear in presenting my problem.

Thanks in advance.

Upvotes: 3

Views: 5229

Answers (1)

IRTFM
IRTFM

Reputation: 263342

Actually I would argue that you did not get a real chi-squared, but instead got an X^2. That might be OK since the sample estimate of a chi-squared variate is often labeled as X^2, but if you want chi you need to use chi (or Chi for capital-Greek-chi that admittedly looks a lot like an "X"). You need to use double quotes and construct as a plotmath expression with proper ~ and * separators:

                      lab2 = c("chi^2*':'~18.5*', p =3e-04'",
                               "chi^2*':'~4.7*', p =0.1909'",
                               "chi^2*':'~15.3*', p =0.0016'")

Run the examples and demos for plotmath:

?plotmath
demo(plotmath)

Upvotes: 2

Related Questions