r - 如何为 ggplot 绘图编写测试

标签 r unit-testing testing ggplot2 testthat

我有很多生成图的函数,通常是 ggplot2。现在,我正在生成绘图并测试基础数据。但我想知道是否有合理的方法来测试绘图是否包含我期望的图层/选项,或者图形元素是否符合期望。

例如:

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(...,...)
})

也许有更直接的方法?

最佳答案

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

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

question and its answers为表征 ggplot 对象的其他方法提供了一个很好的起点,以防您有其他想要测试的东西。

关于r - 如何为 ggplot 绘图编写测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31038709/

相关文章:

使用 promises 测试 ember 组件

r - 如何从列表中向 R 数据框添加多列

r - 如何在ggplot2中限制调色板

python - 如何将 Python 单元测试指定为具有数据库依赖性?

python - 如何从 pytest 回溯中删除库代码调用?

unit-testing - 我需要帮助来生成对 angular6 中可观察到的 fromEvent 的测试

r - 如何使用 R 阅读电子邮件

r - 使用 plyr 在两列上加入两个海量数据帧

c# - Xunit 和 Mock 数据与最小起订量

python - 如何在 Python 测试期间替换方法?