使用plotly使用按钮打开和关闭多个注释

时间:2017-06-28 18:05:10

标签: r plotly

我用plotly创建了一个带有多个注释的图。这是我的代码,它按预期工作:

library(plotly)
a <- 1:10
b <- 1:10
data <- data.frame(a,b)

annotations <- list(x = a[3:4],
                    y = b[3:4],
                    text = c("p1","p2"),
                    showarrow = TRUE)

updatemenus <- list(
  list(
    type= 'buttons',
    buttons = list(
      list(
        label = "ON",
        method = "update",
        args = list(list(),
                    list(annotations = list(annotations)))),
      list(
        label = "OFF",
        method = "update",
        args = list(list(),
                    list(annotations = list(c()))))
    )
  )
)

p <- plot_ly(data = data, x = ~a, y = ~b, type = "scatter", mode = "lines")
p <- layout(p, updatemenus = updatemenus)
p

This is the plot I get

但我无法弄清楚如何正确实现按钮来打开和关闭注释。我下面的代码实现了按钮,但是当我使用它们时,只显示一个箭头,它不合适,没有文字。

Elpy Configuration

Virtualenv........: None
RPC Python........: 3.5.3 (/usr/bin/python3.5)
Interactive Python: /usr/bin/python3.5 (/usr/bin/python3.5)
Emacs.............: 24.5.1
Elpy..............: 1.10.0
Jedi..............: 0.10.2
Rope..............: 0.10.5
Importmagic.......: 0.1.7
Autopep8..........: 0.1.7
Syntax checker....: flake8 (/usr/local/bin/flake8)

You have not activated a virtual env. While Elpy supports this, it is
often a good idea to work inside a virtual env. You can use M-x
pyvenv-activate or M-x pyvenv-workon to activate a virtual env.

The directory ~/.local/bin/ is not in your PATH. As there is no active
virtualenv, installing Python packages locally will place executables
in that directory, so Emacs won't find them. If you are missing some
commands, do add this directory to your PATH.

Options

`Raised' text indicates buttons; type RET or click mouse-1 on a button
to invoke its action.  Invoke [+] to expand a group, and [-] to
collapse an expanded group.  Invoke the [Group], [Face], and [Option]
buttons below to edit that item in another window.

The plot looks like this when I use the ON button.

如果有人能在这里帮助我,或者向我展示一些实现可以切换的注释的替代方法,那将是很好的。

1 个答案:

答案 0 :(得分:1)

您可以使用for looplapply。例如:

library(plotly)
a <- 1:10
b <- 1:10
text <- LETTERS[seq(1,10)]
data <- data.frame(a,b,text)

annotations = list()
for (i in 1:length(data[,1])) {
  annotation <- list(x = data$a[i],
                      y = data$b[i],
                      text = data$text[i],
                      showarrow = TRUE)
  annotations[[i]] <- annotation
}

updatemenus <- list(
  list(
    type= 'buttons',
    buttons = list(
      list(
        label = "ON",
        method = "update",
        args = list(list(),
                    list(annotations = annotations))),
      list(
        label = "OFF",
        method = "update",
        args = list(list(),
                    list(annotations = list(c()))))
    )
  )
)

p <- plot_ly(data = data, x = ~a, y = ~b, type = "scatter", mode = "lines")
p <- layout(p, annotations = annotations, updatemenus = updatemenus)
p