diff --git a/R/plotly_build.R b/R/plotly_build.R index daf3c86845..764f793dcd 100644 --- a/R/plotly_build.R +++ b/R/plotly_build.R @@ -128,6 +128,11 @@ plotly_build.plotly <- function(p, registerFrames = TRUE) { }) } + errorPaths <- list( + c("error_x", "array"), c("error_x", "arrayminus"), + c("error_y", "array"), c("error_y", "arrayminus") + ) + dats <- Map(function(x, y) { # grab the data for this trace @@ -210,7 +215,26 @@ plotly_build.plotly <- function(p, registerFrames = TRUE) { if (inherits(tr[[i]], "AsIs")) builtData[[i]] <- I(builtData[[i]]) } - if (NROW(builtData) > 0) { + inputRows <- nrow(builtData) + errorArrays <- list() + if (inputRows > 0) { + # Histograms index errors by bin. + # Segments and ribbons take error arrays in output vertex order. + if (trace[["type"]] != "histogram" && + !inherits(trace, c("plotly_segment", "plotly_ribbon")) && + any(c("error_x", "error_y") %in% names(trace))) { + errorArrays <- lapply(errorPaths, function(path) { + values <- purrr::pluck(trace, path[[1]], path[[2]]) + if (is.null(dim(values)) && !inherits(values, "JS_EVAL") && + (is.atomic(values) || is.list(values))) { + values + } + }) + if (any(lengths(errorArrays) > 0)) { + builtData[[".plotlyErrorRow"]] <- seq_len(inputRows) + } + } + # Build the index used to split one "trace" into multiple traces isAsIs <- vapply(builtData, function(x) inherits(x, "AsIs"), logical(1)) isDiscrete <- vapply(builtData, is.discrete, logical(1)) @@ -263,40 +287,69 @@ plotly_build.plotly <- function(p, registerFrames = TRUE) { } # TODO: provide a better way to clean up "high-level" attrs trace[c("ymin", "ymax", "yend", "xend")] <- NULL - trace[lengths(trace) > 0] + list( + trace = trace[lengths(trace) > 0], inputRows = inputRows, errorArrays = errorArrays + ) }, attrsToEval, names2(attrsToEval)) p$x$attrs <- lapply(p$x$attrs, function(x) structure(x, class = "plotly_eval")) - # traceify by the interaction of discrete variables - traces <- list() - for (i in seq_along(dats)) { - d <- dats[[i]] - scaleAttrs <- names(d) %in% paste0(npscales(), "s") - traces <- c(traces, traceify(d[!scaleAttrs], d$.plotlyTraceIndex)) - if (i == 1) traces[[1]] <- c(traces[[1]], d[scaleAttrs]) - } - # insert NAs to differentiate groups - traces <- lapply(traces, function(x) { - d <- tibble::as_tibble(x[names(x) %in% x$.plotlyVariableMapping]) + groupTrace <- function(x, source) { + mapping <- x$.plotlyVariableMapping + if (length(x$.plotlyErrorRow)) { + # The column names describe the whole trace and must survive the split. + mapping <- source$trace$.plotlyVariableMapping + } + d <- tibble::as_tibble(x[names(x) %in% mapping]) d <- group2NA( d, if (has_group(x)) ".plotlyGroupIndex", ordered = if (inherits(x, "plotly_line")) "x", retrace.first = inherits(x, "plotly_polygon") ) - for (i in x$.plotlyVariableMapping) { + for (i in mapping) { # try to reduce the amount of data we have to send for non-positional scales entry <- if (i %in% npscales()) uniq(d[[i]]) else d[[i]] if (is.null(entry)) { - x[[i]] <- NULL + x[[i]] <- NULL } else { - x[[i]] <- structure(entry, class = oldClass(x[[i]])) + x[[i]] <- structure(entry, class = oldClass(x[[i]])) } } + + rows <- d[[".plotlyErrorRow"]] + if (length(rows)) { + # Keep the full arrays when the trace keeps its original rows. + sameRows <- identical(rows, seq_len(source$inputRows)) + for (i in which(lengths(source$errorArrays) > 0)) { + values <- source$errorArrays[[i]] + if (!sameRows) { + missing <- which(rows > length(values)) + values <- values[rows] + if (length(missing)) { + # Plotly.js treats null as zero and "NaN" as a missing error. + values <- unname(as.list(values)) + values[missing] <- list("NaN") + } + } + x[[errorPaths[[i]]]] <- values + } + } + x[[".plotlyErrorRow"]] <- NULL x - }) + } + + # traceify by the interaction of discrete variables + traces <- list() + for (i in seq_along(dats)) { + source <- dats[[i]] + d <- source$trace + scaleAttrs <- names(d) %in% paste0(npscales(), "s") + splitTraces <- traceify(d[!scaleAttrs], d$.plotlyTraceIndex) + if (i == 1) splitTraces[[1]] <- c(splitTraces[[1]], d[scaleAttrs]) + traces <- c(traces, lapply(splitTraces, groupTrace, source = source)) + } # Map special plot_ly() arguments to plotly.js trace attributes. # Note that symbol/linetype can modify the mode, so those are applied first diff --git a/tests/testthat/test-grouped-error-arrays.R b/tests/testthat/test-grouped-error-arrays.R new file mode 100644 index 0000000000..c3cbaaf3f2 --- /dev/null +++ b/tests/testthat/test-grouped-error-arrays.R @@ -0,0 +1,183 @@ +test_that("y error arrays follow points when color splits a trace", { + data <- data.frame( + x = 1:6, + y = 11:16, + group = rep(c("B", "A"), 3), + upper = 21:26, + lower = 31:36 + ) + p <- plot_ly( + data, x = ~x, y = ~y, color = ~group, type = "scatter", mode = "markers", + error_y = list(array = ~upper, arrayminus = ~lower, symmetric = FALSE) + ) + traces <- plotly_build(p)$x$data + + expect_length(traces, 2) + for (trace in traces) { + rows <- match(trace$x, data$x) + expect_equal(as.vector(trace$error_y$array), data$upper[rows]) + expect_equal(as.vector(trace$error_y$arrayminus), data$lower[rows]) + expect_false(trace$error_y$symmetric) + } +}) + +test_that("y error arrays stay aligned in a seven-row color split", { + data <- data.frame(x = 1:7, y = 11:17, group = rep(c("A", "B"), length.out = 7)) + p <- plot_ly( + data, x = ~x, y = ~y, color = ~group, type = "scatter", mode = "markers", + error_y = list(array = 21:27) + ) + traces <- plotly_build(p)$x$data + + expect_length(traces, 2) + for (trace in traces) { + expect_equal(as.vector(trace$error_y$array), (21:27)[trace$x]) + } +}) + +test_that("y error arrays follow a line through a gap in a color split", { + data <- data.frame( + x = 1:8, y = c(11, 12, NA, 14:18), + group = rep(c("A", "B"), c(5, 3)), upper = 21:28 + ) + p <- plot_ly( + data, x = ~x, y = ~y, color = ~group, type = "scatter", mode = "lines+markers", + error_y = list(array = ~upper) + ) + traces <- plotly_build(p)$x$data + + expect_length(traces, 2) + expect_equal(as.vector(traces[[1]]$x), c(1, 2, NA, 4, 5)) + for (trace in traces) { + expect_equal(as.vector(trace$error_y$array), data$upper[trace$x]) + } +}) + +test_that("x error arrays follow points when symbol splits a line trace", { + data <- data.frame( + x = c(5, 6, 3, 4, 1, 2), + y = c(11, 12, NA, 14, 15, 16), + group = rep(c("B", "A"), 3), + upper = 21:26, + lower = 31:36 + ) + p <- plot_ly(data, x = ~x, y = ~y, symbol = ~group) %>% + add_lines(error_x = ~list( + array = upper, arrayminus = as.list(lower), symmetric = FALSE + )) + traces <- plotly_build(p)$x$data + + expect_length(traces, 2) + for (trace in traces) { + rows <- match(trace$x, data$x) + expect_equal(as.vector(trace$error_x$array), data$upper[rows]) + expect_equivalent(trace$error_x$arrayminus, as.list(data$lower)[rows]) + } +}) + +test_that("short error arrays preserve missing values when groups are sorted", { + data <- data.frame(x = c(3, 2, 1, 4), y = 11:14, group = c("A", "B", "A", "B")) + p <- plot_ly(data, x = ~x, y = ~y, color = ~group) %>% + add_lines(error_y = list(array = c(21, 22), arrayminus = list(31, 32))) + traces <- jsonlite::parse_json(plotly_json(p, jsonedit = FALSE))$data + + expect_length(traces, 2) + for (trace in traces) { + rows <- match(unlist(trace$x), data$x) + expect_equal(trace$error_y$array, list(21, 22, "NaN", "NaN")[rows]) + expect_equal(trace$error_y$arrayminus, list(31, 32, "NaN", "NaN")[rows]) + } +}) + +test_that("short named error vectors serialize as arrays in each color group", { + data <- data.frame(x = 1:4, y = 11:14, group = c("A", "B", "A", "B")) + p <- plot_ly( + data, x = ~x, y = ~y, color = ~group, type = "scatter", mode = "markers", + error_y = list( + array = c(first = 21, second = 22), + arrayminus = c(first = 31, second = 32), symmetric = FALSE + ) + ) + traces <- jsonlite::parse_json(plotly_json(p, jsonedit = FALSE))$data + + expect_length(traces, 2) + for (trace in traces) { + rows <- unlist(trace$x) + expect_equal(trace$error_y$array, list(21, 22, "NaN", "NaN")[rows]) + expect_equal(trace$error_y$arrayminus, list(31, 32, "NaN", "NaN")[rows]) + } +}) + +test_that("style can add points with pre-supplied upper and lower errors", { + p <- plot_ly( + x = 1:2, y = 11:12, type = "scatter", mode = "markers", + error_y = list(array = 21:24, arrayminus = 31:34, symmetric = FALSE) + ) + p <- style(p, x = 1:4, y = 11:14) + trace <- jsonlite::parse_json(plotly_json(p, jsonedit = FALSE))$data[[1]] + + expect_equal(unlist(trace$x), 1:4) + expect_equal(unlist(trace$y), 11:14) + expect_equal(unlist(trace$error_y$array), 21:24) + expect_equal(unlist(trace$error_y$arrayminus), 31:34) +}) + +test_that("building a trace preserves JavaScript error array expressions", { + errors <- htmlwidgets::JS("[2, 4, 6]") + p <- plot_ly(x = 1:3, y = 11:13, type = "scatter", mode = "markers", + error_y = list(array = errors)) + + expect_s3_class(plotly_build(p)$x$data[[1]]$error_y$array, "JS_EVAL") +}) + +test_that("segment error arrays refer to the output vertices", { + p <- add_segments(plot_ly(), x = 1, y = 2, xend = 3, yend = 4, + error_y = list(array = 5)) + trace <- plotly_build(p)$x$data[[1]] + + expect_equal(as.vector(trace$x), c(1, 3)) + expect_equal(as.vector(trace$error_y$array), 5) +}) + +test_that("ribbon error arrays refer to the output vertices", { + p <- add_ribbons(plot_ly(), x = c(2, 1), ymin = c(3, 2), ymax = c(5, 4), + error_y = list(array = c(6, 7))) + trace <- plotly_build(p)$x$data[[1]] + + expect_equal(as.vector(trace$x), c(1, 2, 2, 2, 1)) + expect_equal(as.vector(trace$error_y$array), c(6, 7)) +}) + +test_that("histograms retain bin errors when there are fewer samples than bins", { + upper <- c(0.1, 0.2, 0.3) + lower <- c(0.4, 0.5, 0.6) + p <- add_histogram( + plot_ly(), x = c(0.1, 2.1), xbins = list(start = 0, end = 3, size = 1), + error_y = list(array = upper, arrayminus = lower, symmetric = FALSE) + ) + trace <- plotly_build(p)$x$data[[1]] + + expect_equal(as.vector(trace$error_y$array), upper) + expect_equal(as.vector(trace$error_y$arrayminus), lower) +}) + +test_that("color groups retain horizontal histogram bin errors", { + data <- data.frame( + y = c(0.1, 0.2, 1.1, 1.2, 2.1, 2.2, 2.3, 2.4), + group = rep(c("A", "B"), 4) + ) + upper <- c(0.1, 0.2, 0.3) + lower <- c(0.4, 0.5, 0.6) + p <- plot_ly( + data, y = ~y, color = ~group, type = "histogram", + ybins = list(start = 0, end = 3, size = 1), + error_x = list(array = upper, arrayminus = lower, symmetric = FALSE) + ) + traces <- plotly_build(p)$x$data + + expect_length(traces, 2) + for (trace in traces) { + expect_equal(as.vector(trace$error_x$array), upper) + expect_equal(as.vector(trace$error_x$arrayminus), lower) + } +})