1

我最近发表了一篇关于在 ggplot2 ( LINK ) 中向构面添加文本的博文。我想稍微自动化这个过程,所以我做了以下功能。在我尝试使用parse=TRUE. 我的功能不尊重这个论点。我怎样才能像在博客文章中那样在我的函数中适当地使用这个参数?

PS我知道这不是最小的,但实际功能可能对其他人有用。

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
4

1 回答 1

1

当你调用它时,不要传递一个text.df

qfacet_text(x, 33, 2.2, paste("beta ==", 1:6), text.df = NULL, 
    size = 3, color = "grey50", parse = TRUE)
于 2012-09-06T21:13:20.470 回答