Fleetboat
Fleetboat

Reputation: 309

Why is ggplot annotation created with expression and bquote in bold font?

Using ggplot2 I need a multi-line annotation that incorporates variable values, commas, a Greek letter, and a superscript. I played with a lot of different ideas I found in this forum for doing this but nothing I tried worked the way I wanted. I finally adopted a "brute force" method shown in the example code below. The last line of the three-line annotation uses bquote (to include a variable value) and plotmath to add the variable units. The annotation text is fine, but it appears in bold font which is different from the first two lines. I've tried adding "fontface = 'plain'" to all three annotate statements but that doesn't change anything. Is there a way to fix this? I do not want to make all three lines bold. Thanks.

annot_test <- function(){
  require(ggplot2)
  #
  #  Create some data
  #
  x <- c(1:10)
  y <- c(1:10)
  #
  #  Variables to appear in annotation
  #
  day1 <- 201
  dayn <- 210
  station <- c("SU13","SU03","SU05")
  thisYrMn <- 4950
  #
  #  Assemble the text for the annotations
  #
  line1   <- paste("Days: ",day1,"-",dayn,sep="")
  line2   <- paste("Stations: ",
                   station[1],", ",
                   station[2],", ",
                   station[3],sep="")
  line3   <- bquote(paste("Mean: ", .(thisYrMn), 
                          " (",{mu},"g",~m^{-3},")"))
  #
  #  Create the data frame
  #
  df <- data.frame(x,y)
  #
  #  Make a simple plot
  #
  pbase <- ggplot(df, aes(x=x, y=y))
  p1    <- pbase + geom_point()
  
  p1 <- p1 + annotate("text",
             label=line1, 
             x=3.0, 
             y=7.5, 
             hjust=0,
             size=4)
  p1 <- p1 + annotate("text",
             label=line2,
             x=3.0,
             y=7.0,
             size=4,
             hjust=0)
    
  p1 <- p1 + annotate("text",
             label=line3,
             x=3.0,
             y=6.5,
             size=4,
             hjust=0)
  
  print(p1)
}

enter image description here

Upvotes: 1

Views: 1458

Answers (1)

Fleetboat
Fleetboat

Reputation: 309

Thanks to Mikael Jagan's comment, and following up on the error I was getting, the answer is indeed to wrap the bquote call in deparse and use parse = TRUE in the annotate call. The error was caused by the { symbol I was using to offset the mu in the plotmath expression. The corrected code uses:

line3   <- deparse(bquote(paste("Mean: ", .(thisYrMn), 
                          " (",mu,"g",~m^-3,")")))

Upvotes: 1

Related Questions