Plotly legend entry to show/hide all plotting characters

前提是你 提交于 2020-01-02 14:39:50

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!