I have a lot of functions that generate plots, typically with ggplot2. Right now, I'm generating the plot and testing the underlying data. But I'd like to know if there's a reasonable way to test that the plot contains the layers/options I expect it to or that graphical elements match expectations.
For example:
library(ggplot2)
library(scales) # for percent()
library(testthat)
df <- data.frame(
Response = LETTERS[1:5],
Proportion = c(0.1,0.2,0.1,0.2,0.4)
)
#' @export plot_fun
plot_fun <- function(df) {
p1 <- ggplot(df, aes(Response, Proportion)) +
geom_bar(stat='identity') +
scale_y_continuous(labels = percent)
return(p1)
}
test_that("Plot returns ggplot object",{
p <- plot_fun(df)
expect_is(p,"ggplot")
})
test_that("Plot uses correct data", {
p <- plot_fun(df)
expect_that(df, equals(p$data))
})
This is where I'm stuck
test_that("Plot layers match expectations",{
p <- plot_fun(df)
expect_that(...,...)
})
test_that("Scale is labelled percent",{
p <- plot_fun(df)
expect_that(...,...)
})
Perhaps there's a more direct approach?
p$layers
) as are the scales and axis labels (p$labels
). It seems to me you could generate a test function operating on the object. – Popperaes()
call in theplot_fun()
declaration. – Popperggsave
the plot and compare it to the "benchmark" plot (by size, by some hash or pixel by pixel maybe?). You'll have to prepare a full suite of benchmarks by hand, obviously, but that shouldn't be that bad. – Farrel