|
| 1 | +#' Fortify method for x, y, z lists. |
| 2 | +#' |
| 3 | +#' This function turns a list with components x, y, z, such as those used |
| 4 | +#' by \code{\link[graphics]{image}} and \code{\link[graphics]{image}} into |
| 5 | +#' a data frame that can more easily be plotted with ggplot2. |
| 6 | +#' |
| 7 | +#' @export |
| 8 | +#' @param model list with components x, y and z |
| 9 | +#' @param data not used by this method |
| 10 | +#' @param ... not used by this method |
| 11 | +#' @importFrom reshape2 melt |
| 12 | +#' @examples |
| 13 | +#' x <- seq(0, 1, by=0.1) |
| 14 | +#' y <- seq(0, 2, by=0.1) |
| 15 | +#' z <- outer(x, y, "+") |
| 16 | +#' d <- list(x=x, y=y, z=z) |
| 17 | +#' image(d) |
| 18 | +#' persp(d) |
| 19 | +#' head(fortify(d)) |
| 20 | +#' ggplot(d) + geom_tile(aes(x=x, y=y, fill=z)) |
| 21 | +fortify.list <- function(model, data, ...) { |
| 22 | + if ( ! all(names(model) == c("x", "y", "z")) ) { |
| 23 | + stop("ggplot only knows how to deal lists with components x, y, and z, as is suitable for image() or persp()") |
| 24 | + } |
| 25 | + if ( ! is.matrix(model$z) ) { |
| 26 | + stop("element z of the list needs to be a matrix") |
| 27 | + } |
| 28 | + if ( length(model$x) != nrow(model$z) ) { |
| 29 | + stop("element x of the list needs to be the same length at the number of rows of element z") |
| 30 | + } |
| 31 | + if ( length(model$y) != ncol(model$z) ) { |
| 32 | + stop("element y of the list needs to be the same length at the number of columns of element z") |
| 33 | + } |
| 34 | + # convert to data.frame |
| 35 | + d <- melt(model$z) |
| 36 | + names(d) <- c("x", "y", "z") |
| 37 | + # get coordinates |
| 38 | + d$x <- model$x[d$x] |
| 39 | + d$y <- model$y[d$y] |
| 40 | + return(d) |
| 41 | +} |
0 commit comments