如何编写ggplot图的测试 [英] How to write a test for a ggplot plot

查看:120
本文介绍了如何编写ggplot图的测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多函数可以生成图表,通常使用ggplot2。现在,我正在生成情节并测试底层数据。但我想知道是否有合理的方法来测试该情节包含我期望的图层/选项或图形元素是否符合预期。

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))

})

这就是我卡住的地方

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?

推荐答案

这似乎是你的目标,尽管绘制参数和内容的具体要求当然会有所不同。但是对于你在这些测试上面精心制作的例子应该都是通过的:

This seems to be what you're aiming at, though specific requirements for plotting parameters and contents will vary of course. But for the example you nicely crafted above these tests should all pass:

##  Load the proto library for accessing sub-components of the ggplot2
##    plot objects:
library(proto)

test_that("Plot layers match expectations",{
  p <- plot_fun(df)
  expect_is(p$layers[[1]], "proto")
  expect_identical(p$layers[[1]]$geom$objname, "bar")
  expect_identical(p$layers[[1]]$stat$objname, "identity")
})

test_that("Scale is labelled 'Proportion'",{
  p <- plot_fun(df)
  expect_identical(p$labels$y, "Proportion")
})

test_that("Scale range is NULL",{
  p <- plot_fun(df)
  expect_null(p$scales$scales[[1]]$range$range)
})

问题及其答案为描述<的其他方法提供了一个很好的起点code> ggplot 对象,以防您有其他事情需要测试。

This question and its answers offer a good starting point on other ways to characterize ggplot objects in case you have other things you'd like to test.

这篇关于如何编写ggplot图的测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆