manipulation ggtitle ggplot change r unit-testing testing ggplot2 testthat

ggtitle - Cómo escribir una prueba para un diagrama de ggplot



ggplot title center (3)

Esto parece ser lo que pretendes, aunque los requisitos específicos para trazar parámetros y contenidos variarán por supuesto. Pero para el ejemplo que ha elaborado muy bien por encima de estas pruebas, todas deben pasar:

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

Esta pregunta y sus respuestas ofrecen un buen punto de partida sobre otras formas de caracterizar objetos ggplot en caso de que tenga otras cosas que le gustaría probar.

Tengo muchas funciones que generan tramas, generalmente con ggplot2. En este momento, estoy generando la trama y probando los datos subyacentes. Pero me gustaría saber si hay una manera razonable de probar que la trama contiene las capas / opciones que espero o que los elementos gráficos coinciden con las expectativas.

Por ejemplo:

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

Aquí es donde estoy atascado

test_that("Plot layers match expectations",{ p <- plot_fun(df) expect_that(...,...) }) test_that("Scale is labelled percent",{ p <- plot_fun(df) expect_that(...,...) })

Tal vez hay un enfoque más directo?


Lo que también considero útil, además de las respuestas existentes, es probar si realmente se puede imprimir un diagrama.

library(ggplot2) library(scales) # for percent() library(testthat) # First, ''correct'' data frame df <- data.frame( Response = LETTERS[1:5], Proportion = c(0.1,0.2,0.1,0.2,0.4) ) # Second data frame where column has ''wrong'' name that does not match aes() df2 <- data.frame( x = LETTERS[1:5], Proportion = c(0.1,0.2,0.1,0.2,0.4) ) plot_fun <- function(df) { p1 <- ggplot(df, aes(Response, Proportion)) + geom_bar(stat=''identity'') + scale_y_continuous(labels = percent) return(p1) } # All tests succeed test_that("Scale is labelled ''Proportion''",{ p <- plot_fun(df) expect_true(is.ggplot(p)) expect_identical(p$labels$y, "Proportion") p <- plot_fun(df2) expect_true(is.ggplot(p)) expect_identical(p$labels$y, "Proportion") }) # Second test with data frame df2 fails test_that("Printing ggplot object actually works",{ p <- plot_fun(df) expect_error(print(p), NA) p <- plot_fun(df2) expect_error(print(p), NA) }) #> Error: Test failed: ''Printing ggplot object actually works'' #> * `print(p)` threw an error. #> Message: object ''Response'' not found #> Class: simpleError/error/condition


Vale la pena señalar que el paquete vdiffr está diseñado para comparar gráficos. Una buena característica es que se integra con el paquete testthat, en realidad se usa para probar en ggplot2, y tiene un complemento para RStudio para ayudar a administrar su suite de pruebas.