1

I recently did a blog post about adding text to facets in ggplot2 (LINK). I wanted to automate this process a bit so I made the following function. I thought I had great success until I tried to use parse=TRUE. My function is not respecting this argument. How can I use this argument inside my function appropriately as I did in the blog post?

PS I know this isn't exactly minimal but the actual function may be useful to others.

qfacet_text <- function(ggplot2.object, x.coord, y.coord, labels = NULL, 
    text.df = NULL, ...) {
    dat <- ggplot2.object$data
    rows <- ggplot2.object$facet[[1]][[1]]
    cols <- ggplot2.object$facet[[2]][[1]]
    fcol <- dat[, as.character(cols)]
    frow <- dat[, as.character(rows)]
    len <- length(levels(fcol)) *  length(levels(frow))
    vars <- data.frame(expand.grid(levels(frow), levels(fcol)))
    colnames(vars) <- c(as.character(rows), as.character(cols))
    if (is.null(labels)) {
        labels <- LETTERS[1:len]
    }
    if (length(x.coord) == 1) {
       x.coord <- rep(x.coord, len)
    }
    if (length(y.coord) == 1) {
       y.coord <- rep(y.coord, len)
    }
    if (is.null(text.df)) {
        text.df <- data.frame(x = x.coord, y = y.coord, vars, labs=labels)
    } 
    p <- ggplot2.object + geom_text(aes(x, y, label=labs, group=NULL), 
        data=text.df, ...)
    print(p)
    invisible(list(original = ggplot2.object, new = p, dat = text.df))
}

mtcars[, c("cyl", "am", "gear")] <- lapply(mtcars[, c("cyl", "am", "gear")], as.factor)

x <- ggplot(mtcars, aes(mpg, wt, group = cyl)) + 
    geom_line(aes(color=cyl)) +
    geom_point(aes(shape=cyl)) + 
    facet_grid(gear ~ am) +
    theme_bw()  

z <- qfacet_text(x, 33, 2.2, 1:6, color="red")     #as expected
z$dat[5, 1:2] <- c(15, 5)
qfacet_text(x, 33, 2.2, paste("beta ==", 1:6), text.df = z$dat, 
    size = 3, color = "grey50", parse = TRUE)  #doesn't parse
1
  • It's interesting that if you try to construct an expression for 'labels', that the error report is: "Error in as.data.frame.default(x[[i]], optional = TRUE) : cannot coerce class '"expression"' into a data.frame" Commented Sep 6, 2012 at 21:27

1 Answer 1

1

When you call it, don't pass a text.df

qfacet_text(x, 33, 2.2, paste("beta ==", 1:6), text.df = NULL, 
    size = 3, color = "grey50", parse = TRUE)
Sign up to request clarification or add additional context in comments.

1 Comment

I did exactly that and the problem is that I just re-fed the data frame from the first plot. Thanks for helping me see that. Bad coding.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.