Skip to content

Commit 20b7ad7

Browse files
committed
restrict exists to plotly environment
1 parent 6ff8831 commit 20b7ad7

File tree

2 files changed

+54
-5
lines changed

2 files changed

+54
-5
lines changed

R/ggplotly.R

+4-5
Original file line numberDiff line numberDiff line change
@@ -625,7 +625,7 @@ gg2list <- function(p) {
625625

626626
# Legend.
627627
layout$margin$r <- 10
628-
if (exists("increase_margin_r")) {
628+
if (exists("increase_margin_r", where = as.environment("package:plotly"))) {
629629
layout$margin$r <- 60
630630
}
631631
layout$legend <- list(bordercolor="transparent",
@@ -666,11 +666,10 @@ gg2list <- function(p) {
666666
legend.title <- colnames(p$data)[i]
667667
}
668668
legend.title <- paste0("<b>", legend.title, "</b>")
669-
670669
# Create legend title element as an annotation
671-
if (exists("annotations")) {
672-
nann <- nann + 1
673-
} else {
670+
if (exists("annotations", where = as.environment("package:plotly"))) {
671+
nann <- nann + 1
672+
} else{
674673
annotations <- list()
675674
nann <- 1
676675
}
+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
context("Objects and Environments")
2+
3+
# Expect trace function
4+
expect_traces <- function(gg, n_traces, name) {
5+
stopifnot(is.ggplot(gg))
6+
stopifnot(is.numeric(n_traces))
7+
save_outputs(gg, paste0("object_environments-", name))
8+
L <- gg2list(gg)
9+
all_traces <- L$data
10+
no_data <- sapply(all_traces, function(tr) {
11+
is.null(tr[["x"]]) && is.null(tr[["y"]])
12+
})
13+
has_data <- all_traces[!no_data]
14+
expect_equal(length(has_data), n_traces)
15+
list(traces = has_data, layout = L$layout)
16+
}
17+
18+
# make data
19+
set.seed(955)
20+
dat <- data.frame(cond = rep(c("A", "B"), each=10),
21+
xvar = 1:20 + rnorm(20,sd=3),
22+
yvar = 1:20 + rnorm(20,sd=3))
23+
24+
# make ggplot
25+
p <- ggplot(dat, aes(x = xvar, y = yvar, color = cond)) +
26+
geom_point() + xlab("X") + ylab("Y")
27+
28+
# Test 1: annotation
29+
test_that("object annotations in environment outside plotly", {
30+
annotations <- "outside of the plotly environment"
31+
info <- expect_traces(p, 2, "annotations")
32+
tr <- info$traces[[1]]
33+
la <- info$layout
34+
expect_identical(tr$type, "scatter")
35+
expect_identical(la$xaxis$title, "X")
36+
expect_identical(la$yaxis$title, "Y")
37+
expect_true(grepl("cond", la$annotations[[1]]$text))
38+
})
39+
40+
# Test 2: increase_margin_r
41+
test_that("object increase_margin_r in environment outside plotly", {
42+
increase_margin_r <- "outside of the plotly environment"
43+
info <- expect_traces(p, 2, "increase_margin_r")
44+
tr <- info$traces[[1]]
45+
la <- info$layout
46+
expect_identical(la$xaxis$title, "X")
47+
expect_identical(la$yaxis$title, "Y")
48+
expect_identical(tr$type, "scatter")
49+
expect_true(grepl("cond", la$annotations[[1]]$text))
50+
})

0 commit comments

Comments
 (0)