One slider controlling multiple subplots in R

大兔子大兔子 提交于 2021-02-20 02:45:50

问题


I want to use one slider to control multiple subplots created with plotly. I found answers in Python like these two:

  • Plot.ly. Using slider control with multiple plots
  • https://community.plot.ly/t/using-one-slider-to-control-multiple-subplots-not-multiple-traces/13955/4

Example (second link):

import plotly.graph_objs as go
from plotly.tools import make_subplots

fig = make_subplots(1, 2)

fig.add_scatter(y=[1, 3, 2], row=1, col=1, visible=True)
fig.add_scatter(y=[3, 1, 1.5], row=1, col=1, visible='legendonly')
fig.add_scatter(y=[2, 2, 1], row=1, col=1, visible='legendonly')
fig.add_scatter(y=[1, 3, 2], row=1, col=2, visible=True)
fig.add_scatter(y=[1.5, 2, 2.5], row=1, col=2, visible='legendonly')
fig.add_scatter(y=[2.5, 1.2, 2.9], row=1, col=2, visible='legendonly')

steps = []
for i in range(3):
    step = dict(
        method = 'restyle',  
        args = ['visible', ['legendonly'] * len(fig.data)],
    )
    step['args'][1][i] = True
    step['args'][1][i+3] = True
    steps.append(step)

sliders = [dict(
    steps = steps,
)]

fig.layout.sliders = sliders

go.FigureWidget(fig)

But how can I realize this in R?


回答1:


It's actually quite the same procedure as in python. Here is an example derived from this:

library(plotly)

df <- data.frame(x = 1:5, 
                 y = 1:5) 

# create steps for slider
steps <- list(
  list(args = list("marker.color", "red"), 
       label = "Red", 
       method = "restyle", 
       value = "1"
  ),
  list(args = list("marker.color", "green"), 
       label = "Green", 
       method = "restyle", 
       value = "2"
  ),
  list(args = list("marker.color", "blue"), 
       label = "Blue", 
       method = "restyle", 
       value = "3"
  )
)

p1 <- p2 <- df %>%
  plot_ly(x = ~x, y = ~y,
          mode = "markers", 
          marker = list(size = 20,
                        color = 'green'), 
          type = "scatter")

p <- subplot(p1, p2) %>%
  layout(title = "Basic Slider",
         sliders = list(
           list(
             active = 1, 
             currentvalue = list(prefix = "Color: "), 
             pad = list(t = 60), 
             steps = steps))) 

p



来源:https://stackoverflow.com/questions/58713761/one-slider-controlling-multiple-subplots-in-r

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