问题
Suppose I am building a plotly scatterplot that displays three different groups (here specified by colour). I can show/hide each group individually by clicking at the groups in the legend.
library(ggplot2)
library(plotly)
d <- data.frame("a" = sample(1:50, 20, T), "b" = sample(1:50, 20, T),
"col" = factor(sample(1:3, 20, T)))
gg <- ggplot() + geom_point(aes(x = a, y = b, color = col), data = d)
gg
plotly_build(gg)
Is there a way to add a button to the legend to show/hide all points ?
回答1:
I don't know of a way to toggle all points simultaneously, but (as indicated in the comments that this would be a suitable alternative) it is possible to start with them all hidden and make points visible one at a time
plot_ly(data=d, x=a, y=b, type='scatter', mode='markers', color=col, visible='legendonly')
回答2:
This may be closer to what was originally asked for, but it is just a "button" not a legend entry, so placement is difficult.
library(ggplot2)
library(plotly)
d <- data.frame("a" = sample(1:50, 20, T), "b" = sample(1:50, 20, T),
"col" = factor(sample(1:3, 20, T)))
gg <- ggplot() + geom_point(aes(x = a, y = b, color = col), data = d)
gg
plotly_build(gg) %>%
layout(updatemenus = list(
list(
type = "buttons",
direction = "right",
xanchor = "center",
yanchor = "top",
showactive = FALSE,
x = 1.05,
y = 0.2,
buttons = list(
list(method = "restyle",
args = list("visible", "all"),
label = "show all"),
list(method = "restyle",
args = list("visible", "legendonly"),
label = "hide all")
)
)
))
This produces (depending on the version of plotly) the following drop-down "buttons":
I don't know how to dynamically update the buttons based on the current visibility or how to make both buttons permanently visible instead of only available through the drop-down menu.
来源:https://stackoverflow.com/questions/38015075/plotly-legend-entry-to-show-hide-all-plotting-characters