How Can I Make geom_label Display Slightly Complex R Regular Expressions?

343 views
Skip to first unread message

Donald Macnaughton

unread,
Jun 14, 2017, 5:55:05 PM6/14/17
to ggplot2
Hello Group,

I would like to be able to have ggplot show parsed R regular expressions in labels on plots. In particular, I would like to display the string
Area a1
where the second "a" is in italics, and the 1 is a subscript. Here's some code to produce the problem:

# The following approaches work work properly with parse=TRUE:
# label = "italic(a[1])"
# label = "plain(Area)"

# But the following DON'T WORK:
# label = "plain(Area ) italic(a[1])"
# label = "plain(Area ), italic(a[1])"

# Note that the PDF ggplot2 manual for version 2.2.1 says on page 74 that
# "geom_text uses strings, not expressions". The geom_label function and 
# the geom_text function are variants, both described under the heading
# geom_label.

# Regular expressions in R 3.4.0 are described in the Reference Index manual
# under  plotmath  beginning on page 752.

library(ggplot2)

x <- c(1,2)
y <- c(3,4)
df <- data.frame(x,y)
ggplot(df, aes(x,y)) +  geom_path() + 
geom_label(label="plain(Area ) italic(a[1])", x=1.5,y=3.75,parse=TRUE)


Thank you for your help,

Don Macnaughton

Olivia

unread,
Jul 4, 2017, 10:48:28 PM7/4/17
to ggplot2
Try the following:

ggplot(df, aes(x,y)) +  geom_path() + 
geom_label(label="plain(Area )~italic(a[1])", x=1.5,y=3.75,parse=TRUE)

Replace the ~ with a * if you prefer no gap in other settings.

Cheers,

Olivia
Reply all
Reply to author
Forward
0 new messages