Skip to content

Commit b6afa97

Browse files
committed
Keep error bars aligned when color or symbol splits a trace
Signed-off-by: Kush Patel <56747429+kshptl@users.noreply.github.com>
1 parent 4ff1c33 commit b6afa97

2 files changed

Lines changed: 253 additions & 17 deletions

File tree

‎R/plotly_build.R‎

Lines changed: 70 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,11 @@ plotly_build.plotly <- function(p, registerFrames = TRUE) {
128128
})
129129
}
130130

131+
errorPaths <- list(
132+
c("error_x", "array"), c("error_x", "arrayminus"),
133+
c("error_y", "array"), c("error_y", "arrayminus")
134+
)
135+
131136
dats <- Map(function(x, y) {
132137

133138
# grab the data for this trace
@@ -210,7 +215,26 @@ plotly_build.plotly <- function(p, registerFrames = TRUE) {
210215
if (inherits(tr[[i]], "AsIs")) builtData[[i]] <- I(builtData[[i]])
211216
}
212217

213-
if (NROW(builtData) > 0) {
218+
inputRows <- nrow(builtData)
219+
errorArrays <- list()
220+
if (inputRows > 0) {
221+
# Histograms index errors by bin.
222+
# Segments and ribbons take error arrays in output vertex order.
223+
if (trace[["type"]] != "histogram" &&
224+
!inherits(trace, c("plotly_segment", "plotly_ribbon")) &&
225+
any(c("error_x", "error_y") %in% names(trace))) {
226+
errorArrays <- lapply(errorPaths, function(path) {
227+
values <- purrr::pluck(trace, path[[1]], path[[2]])
228+
if (is.null(dim(values)) && !inherits(values, "JS_EVAL") &&
229+
(is.atomic(values) || is.list(values))) {
230+
values
231+
}
232+
})
233+
if (any(lengths(errorArrays) > 0)) {
234+
builtData[[".plotlyErrorRow"]] <- seq_len(inputRows)
235+
}
236+
}
237+
214238
# Build the index used to split one "trace" into multiple traces
215239
isAsIs <- vapply(builtData, function(x) inherits(x, "AsIs"), logical(1))
216240
isDiscrete <- vapply(builtData, is.discrete, logical(1))
@@ -263,40 +287,69 @@ plotly_build.plotly <- function(p, registerFrames = TRUE) {
263287
}
264288
# TODO: provide a better way to clean up "high-level" attrs
265289
trace[c("ymin", "ymax", "yend", "xend")] <- NULL
266-
trace[lengths(trace) > 0]
290+
list(
291+
trace = trace[lengths(trace) > 0], inputRows = inputRows, errorArrays = errorArrays
292+
)
267293

268294
}, attrsToEval, names2(attrsToEval))
269295

270296
p$x$attrs <- lapply(p$x$attrs, function(x) structure(x, class = "plotly_eval"))
271297

272-
# traceify by the interaction of discrete variables
273-
traces <- list()
274-
for (i in seq_along(dats)) {
275-
d <- dats[[i]]
276-
scaleAttrs <- names(d) %in% paste0(npscales(), "s")
277-
traces <- c(traces, traceify(d[!scaleAttrs], d$.plotlyTraceIndex))
278-
if (i == 1) traces[[1]] <- c(traces[[1]], d[scaleAttrs])
279-
}
280-
281298
# insert NAs to differentiate groups
282-
traces <- lapply(traces, function(x) {
283-
d <- tibble::as_tibble(x[names(x) %in% x$.plotlyVariableMapping])
299+
groupTrace <- function(x, source) {
300+
mapping <- x$.plotlyVariableMapping
301+
if (length(x$.plotlyErrorRow)) {
302+
# The column names describe the whole trace and must survive the split.
303+
mapping <- source$trace$.plotlyVariableMapping
304+
}
305+
d <- tibble::as_tibble(x[names(x) %in% mapping])
284306
d <- group2NA(
285307
d, if (has_group(x)) ".plotlyGroupIndex",
286308
ordered = if (inherits(x, "plotly_line")) "x",
287309
retrace.first = inherits(x, "plotly_polygon")
288310
)
289-
for (i in x$.plotlyVariableMapping) {
311+
for (i in mapping) {
290312
# try to reduce the amount of data we have to send for non-positional scales
291313
entry <- if (i %in% npscales()) uniq(d[[i]]) else d[[i]]
292314
if (is.null(entry)) {
293-
x[[i]] <- NULL
315+
x[[i]] <- NULL
294316
} else {
295-
x[[i]] <- structure(entry, class = oldClass(x[[i]]))
317+
x[[i]] <- structure(entry, class = oldClass(x[[i]]))
296318
}
297319
}
320+
321+
rows <- d[[".plotlyErrorRow"]]
322+
if (length(rows)) {
323+
# Keep the full arrays when the trace keeps its original rows.
324+
sameRows <- identical(rows, seq_len(source$inputRows))
325+
for (i in which(lengths(source$errorArrays) > 0)) {
326+
values <- source$errorArrays[[i]]
327+
if (!sameRows) {
328+
missing <- which(rows > length(values))
329+
values <- values[rows]
330+
if (length(missing)) {
331+
# Plotly.js treats null as zero and "NaN" as a missing error.
332+
values <- unname(as.list(values))
333+
values[missing] <- list("NaN")
334+
}
335+
}
336+
x[[errorPaths[[i]]]] <- values
337+
}
338+
}
339+
x[[".plotlyErrorRow"]] <- NULL
298340
x
299-
})
341+
}
342+
343+
# traceify by the interaction of discrete variables
344+
traces <- list()
345+
for (i in seq_along(dats)) {
346+
source <- dats[[i]]
347+
d <- source$trace
348+
scaleAttrs <- names(d) %in% paste0(npscales(), "s")
349+
splitTraces <- traceify(d[!scaleAttrs], d$.plotlyTraceIndex)
350+
if (i == 1) splitTraces[[1]] <- c(splitTraces[[1]], d[scaleAttrs])
351+
traces <- c(traces, lapply(splitTraces, groupTrace, source = source))
352+
}
300353

301354
# Map special plot_ly() arguments to plotly.js trace attributes.
302355
# Note that symbol/linetype can modify the mode, so those are applied first
Lines changed: 183 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
1+
test_that("y error arrays follow points when color splits a trace", {
2+
data <- data.frame(
3+
x = 1:6,
4+
y = 11:16,
5+
group = rep(c("B", "A"), 3),
6+
upper = 21:26,
7+
lower = 31:36
8+
)
9+
p <- plot_ly(
10+
data, x = ~x, y = ~y, color = ~group, type = "scatter", mode = "markers",
11+
error_y = list(array = ~upper, arrayminus = ~lower, symmetric = FALSE)
12+
)
13+
traces <- plotly_build(p)$x$data
14+
15+
expect_length(traces, 2)
16+
for (trace in traces) {
17+
rows <- match(trace$x, data$x)
18+
expect_equal(as.vector(trace$error_y$array), data$upper[rows])
19+
expect_equal(as.vector(trace$error_y$arrayminus), data$lower[rows])
20+
expect_false(trace$error_y$symmetric)
21+
}
22+
})
23+
24+
test_that("y error arrays stay aligned in a seven-row color split", {
25+
data <- data.frame(x = 1:7, y = 11:17, group = rep(c("A", "B"), length.out = 7))
26+
p <- plot_ly(
27+
data, x = ~x, y = ~y, color = ~group, type = "scatter", mode = "markers",
28+
error_y = list(array = 21:27)
29+
)
30+
traces <- plotly_build(p)$x$data
31+
32+
expect_length(traces, 2)
33+
for (trace in traces) {
34+
expect_equal(as.vector(trace$error_y$array), (21:27)[trace$x])
35+
}
36+
})
37+
38+
test_that("y error arrays follow a line through a gap in a color split", {
39+
data <- data.frame(
40+
x = 1:8, y = c(11, 12, NA, 14:18),
41+
group = rep(c("A", "B"), c(5, 3)), upper = 21:28
42+
)
43+
p <- plot_ly(
44+
data, x = ~x, y = ~y, color = ~group, type = "scatter", mode = "lines+markers",
45+
error_y = list(array = ~upper)
46+
)
47+
traces <- plotly_build(p)$x$data
48+
49+
expect_length(traces, 2)
50+
expect_equal(as.vector(traces[[1]]$x), c(1, 2, NA, 4, 5))
51+
for (trace in traces) {
52+
expect_equal(as.vector(trace$error_y$array), data$upper[trace$x])
53+
}
54+
})
55+
56+
test_that("x error arrays follow points when symbol splits a line trace", {
57+
data <- data.frame(
58+
x = c(5, 6, 3, 4, 1, 2),
59+
y = c(11, 12, NA, 14, 15, 16),
60+
group = rep(c("B", "A"), 3),
61+
upper = 21:26,
62+
lower = 31:36
63+
)
64+
p <- plot_ly(data, x = ~x, y = ~y, symbol = ~group) %>%
65+
add_lines(error_x = ~list(
66+
array = upper, arrayminus = as.list(lower), symmetric = FALSE
67+
))
68+
traces <- plotly_build(p)$x$data
69+
70+
expect_length(traces, 2)
71+
for (trace in traces) {
72+
rows <- match(trace$x, data$x)
73+
expect_equal(as.vector(trace$error_x$array), data$upper[rows])
74+
expect_equivalent(trace$error_x$arrayminus, as.list(data$lower)[rows])
75+
}
76+
})
77+
78+
test_that("short error arrays preserve missing values when groups are sorted", {
79+
data <- data.frame(x = c(3, 2, 1, 4), y = 11:14, group = c("A", "B", "A", "B"))
80+
p <- plot_ly(data, x = ~x, y = ~y, color = ~group) %>%
81+
add_lines(error_y = list(array = c(21, 22), arrayminus = list(31, 32)))
82+
traces <- jsonlite::parse_json(plotly_json(p, jsonedit = FALSE))$data
83+
84+
expect_length(traces, 2)
85+
for (trace in traces) {
86+
rows <- match(unlist(trace$x), data$x)
87+
expect_equal(trace$error_y$array, list(21, 22, "NaN", "NaN")[rows])
88+
expect_equal(trace$error_y$arrayminus, list(31, 32, "NaN", "NaN")[rows])
89+
}
90+
})
91+
92+
test_that("short named error vectors serialize as arrays in each color group", {
93+
data <- data.frame(x = 1:4, y = 11:14, group = c("A", "B", "A", "B"))
94+
p <- plot_ly(
95+
data, x = ~x, y = ~y, color = ~group, type = "scatter", mode = "markers",
96+
error_y = list(
97+
array = c(first = 21, second = 22),
98+
arrayminus = c(first = 31, second = 32), symmetric = FALSE
99+
)
100+
)
101+
traces <- jsonlite::parse_json(plotly_json(p, jsonedit = FALSE))$data
102+
103+
expect_length(traces, 2)
104+
for (trace in traces) {
105+
rows <- unlist(trace$x)
106+
expect_equal(trace$error_y$array, list(21, 22, "NaN", "NaN")[rows])
107+
expect_equal(trace$error_y$arrayminus, list(31, 32, "NaN", "NaN")[rows])
108+
}
109+
})
110+
111+
test_that("style can add points with pre-supplied upper and lower errors", {
112+
p <- plot_ly(
113+
x = 1:2, y = 11:12, type = "scatter", mode = "markers",
114+
error_y = list(array = 21:24, arrayminus = 31:34, symmetric = FALSE)
115+
)
116+
p <- style(p, x = 1:4, y = 11:14)
117+
trace <- jsonlite::parse_json(plotly_json(p, jsonedit = FALSE))$data[[1]]
118+
119+
expect_equal(unlist(trace$x), 1:4)
120+
expect_equal(unlist(trace$y), 11:14)
121+
expect_equal(unlist(trace$error_y$array), 21:24)
122+
expect_equal(unlist(trace$error_y$arrayminus), 31:34)
123+
})
124+
125+
test_that("building a trace preserves JavaScript error array expressions", {
126+
errors <- htmlwidgets::JS("[2, 4, 6]")
127+
p <- plot_ly(x = 1:3, y = 11:13, type = "scatter", mode = "markers",
128+
error_y = list(array = errors))
129+
130+
expect_s3_class(plotly_build(p)$x$data[[1]]$error_y$array, "JS_EVAL")
131+
})
132+
133+
test_that("segment error arrays refer to the output vertices", {
134+
p <- add_segments(plot_ly(), x = 1, y = 2, xend = 3, yend = 4,
135+
error_y = list(array = 5))
136+
trace <- plotly_build(p)$x$data[[1]]
137+
138+
expect_equal(as.vector(trace$x), c(1, 3))
139+
expect_equal(as.vector(trace$error_y$array), 5)
140+
})
141+
142+
test_that("ribbon error arrays refer to the output vertices", {
143+
p <- add_ribbons(plot_ly(), x = c(2, 1), ymin = c(3, 2), ymax = c(5, 4),
144+
error_y = list(array = c(6, 7)))
145+
trace <- plotly_build(p)$x$data[[1]]
146+
147+
expect_equal(as.vector(trace$x), c(1, 2, 2, 2, 1))
148+
expect_equal(as.vector(trace$error_y$array), c(6, 7))
149+
})
150+
151+
test_that("histograms retain bin errors when there are fewer samples than bins", {
152+
upper <- c(0.1, 0.2, 0.3)
153+
lower <- c(0.4, 0.5, 0.6)
154+
p <- add_histogram(
155+
plot_ly(), x = c(0.1, 2.1), xbins = list(start = 0, end = 3, size = 1),
156+
error_y = list(array = upper, arrayminus = lower, symmetric = FALSE)
157+
)
158+
trace <- plotly_build(p)$x$data[[1]]
159+
160+
expect_equal(as.vector(trace$error_y$array), upper)
161+
expect_equal(as.vector(trace$error_y$arrayminus), lower)
162+
})
163+
164+
test_that("color groups retain horizontal histogram bin errors", {
165+
data <- data.frame(
166+
y = c(0.1, 0.2, 1.1, 1.2, 2.1, 2.2, 2.3, 2.4),
167+
group = rep(c("A", "B"), 4)
168+
)
169+
upper <- c(0.1, 0.2, 0.3)
170+
lower <- c(0.4, 0.5, 0.6)
171+
p <- plot_ly(
172+
data, y = ~y, color = ~group, type = "histogram",
173+
ybins = list(start = 0, end = 3, size = 1),
174+
error_x = list(array = upper, arrayminus = lower, symmetric = FALSE)
175+
)
176+
traces <- plotly_build(p)$x$data
177+
178+
expect_length(traces, 2)
179+
for (trace in traces) {
180+
expect_equal(as.vector(trace$error_x$array), upper)
181+
expect_equal(as.vector(trace$error_x$arrayminus), lower)
182+
}
183+
})

0 commit comments

Comments
 (0)